teslamotors / informed

A lightweight framework and utility for building powerful forms in React applications
https://teslamotors.github.io/informed
MIT License
956 stars 174 forks source link

validate one field based on another field value #405

Closed bhargavavarma closed 2 years ago

bhargavavarma commented 2 years ago

Describe the bug

We have 2 select fields named select_field1 and select_field2 and both are dependent on each other. when select_field1 value is changing, the select_field2 should also be validated and show error message based on validate function. We are passing select_field1 and its value to useField of select_field2, select_field2 component is re rendering when select_field1 value changes, but the select_field2 error value is not getting set.

joepuzzo commented 2 years ago

Are you using paired validation ??? https://teslamotors.github.io/informed/?path=/story/validation--paired-validation

joepuzzo commented 2 years ago

you should not be trying to use useField or useFieldState at this point. Create your custom inputs once with useField and then you should never be touching that hook again.

joepuzzo commented 2 years ago
<Input
    name="password"
    id="notify-password"
    validate={validatePassword}
    validateOnChange
    validateWhen={['confirmPassword']}
  />
  <Input
    name="confirmPassword"
    id="notify-confirm-password"
    validate={validateConfim}
    validateOnChange
    validateWhen={['password']}
  />
 <button type="submit">Submit</button>
</Form>;
bhargavavarma commented 2 years ago

Are you using paired validation ??? https://teslamotors.github.io/informed/?path=/story/validation--paired-validation

@joepuzzo Both the select fields will have same validate function. In validate function we compare the user selected start date and end date values, if startDate > endDate will return an error.

We have used validateWhen, but also we couldn't achieve the desired output.

joepuzzo commented 2 years ago

did you do exactly as the docs show? Can you recreate issue in a code sandbox https://teslamotors.github.io/informed/?path=/story/playground--format-example

joepuzzo commented 2 years ago

https://codesandbox.io/s/validatepaireddate-71b7pt?file=/App.js

See this example working ^^^^

bhargavavarma commented 2 years ago

https://codesandbox.io/s/validatepaireddate-71b7pt?file=/App.js

See this example working ^^^^

its working. Thankyou @joepuzzo