question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Validating on a field based on multiple separate conditions

See original GitHub issue

I have the following Formik form with a Dropdown and two Date pickers. The date pickers have conditional validation: for both of them, if the user selects the First item from the dropdown, we make the fields required.

However, for the second DatePicker (EndDate) - I want an additional validation that restrict the date to be no more than 6 months from the StartDate and never less than StartDate. And this should only be applied if the user has First as the selected item.

<Formik
    initialValues={{ Dropdown1: "", StartDate: "", EndDate: "" }}
    onSubmit={(values, actions) => {
        setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
        }, 1000);
    }}
    validationSchema={Yup.object().shape({
        StartDate: Yup.date.when("Dropdown1", (data, schema) => {
            data.Dropdown1 === "First" ? schema.required("this is a required field") : schema
        })

        EndDate: Yup.date.when("Dropdown1", (data, schema) => {
            data.Dropdown1 === "First" ? schema.required("this is a required field") : schema

            // Here I need another validation that checks EndDate can't be more than 6 months from StartDate and never less than StartDate
        })
    })}
    render={props => (
    <form onSubmit={props.handleSubmit}>
        <CustomDropdown
            dropdownItems=[
                { caption: "Select something", Id: "" },
                { caption: "First", Id: "1" },
                { caption: "Second", Id: "2" }
            ]
            onBlur={props.handleBlur}
            value={props.values.name}
            name="Dropdown1"
        />
        <CustomDatePicker
            name="StartDate"
        />
        <CustomDatePicker
            name="EndDate"
        />
        {props.errors.name && <div id="feedback">{props.errors.name}</div>}
        <button type="submit">Submit</button>
    </form>
    )}
/>

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

14reactions
jquensecommented, Oct 7, 2019

In there general there are two approaches to doing complex conditional validation:

  1. use when(), it supports specifying multiple dependencies like when(['startDate' 'endDate], () => `. This approach is good for directed conditions, e.g. dependencies with no cycles, because it ensures fields are processed in the correct order (topographically). If you have cycles tho it doesn’t work super well (e.g. startDate depends on EndDate which depends on startDate)

  2. Move validation to a parent. You can declare a custom test on the parent object that compares all the child values and throws the right error, this is the most straight forward approach but is a bit harder to make work with Form libraries that expect all errors to be keyed by a fields specific path. You have to get a bit creative with error displaying, which i don’t think is a bad thing, heavily interdependent fields don’t always map neatly to a single field’s error, and may require more intentional UI anyway.

2reactions
dwandertoncommented, Sep 20, 2022

Is there currently an issue open regarding the typing failure as mentioned by @builtbyjay above, @jquense? Couldn’t spot one, given I’m new to TS another person might be better at defining the issue / opening an issue.

Screen Shot 2022-09-20 at 7 51 55 PM
Read more comments on GitHub >

github_iconTop Results From Across the Web

java - How can I validate two or more fields in combination?
I now have a situation where the combination of two fields has to be validated: public class MyModel { public Integer getValue1() {...
Read more >
How to Create Validation Rules with Multiple Conditions
Salesforce #SalesforceSupport #SalesforceHowToAfter watching this screencast the user will be able to learn how to create validation rules ...
Read more >
Multiple OR statements in Validation Rule
Save this question. Show activity on this post. Im trying to figure out a Validation Rule IF Picklist Value is "Yes", then 4...
Read more >
How to validate a document for multiple conditions(data type ...
I am trying to perform multiple validations (data type, mandatory, min max length) on different fields for a document.
Read more >
Restrict data input by using validation rules - Microsoft Support
You can compare values across different fields using a record validation rule. For example, a record with two date fields might require that...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found