Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux Form Dynamic Field Level Validation

I have a dynamic form field that is required based on the value of a form selected field. ie If the value of a certain field is "Yes" then the comment box is required and if "No" then it is not required.

If I initially select "Yes" and touch and blur the comment field the validation will return the required error. But after if I switch to "No" and back to "Yes" the validation error no longer occurs. If I type into the comment box and remove the validation will occur again.

I am using field level validation and have also use sync validation with the same issue.

<Field name={`${fieldId}.comment`}  validate={condition.required ? [required] : []} label={condition.label} className="form-control" component={renderTextField} />

Where condition is the check to see whether the field should be required.

The logic is correct as the validation work on initial selection and if you fill the comment field and remove the text but it just does not seem to receive the validation error.

Thanks in advance

like image 461
Sergio Pellegrini Avatar asked Jan 31 '23 01:01

Sergio Pellegrini


1 Answers

Quote from the Redux-Form Field component docs (v 6.8.0):

validate : (value, allValues, props) => error [optional]

Allows you to to provide a field-level validation rule. The function will be given the current value of the field, all the other form values, and any props passed to the form. If the field is valid, it should return undefined, if the field is invalid, it should return an error (usually, but not necessarily, a String).

You're trying to pass the error value in to the Field directly, but the validate prop is meant to accept a validation function that is used to determine validity. You should do something like this:

const validateComment = (value, allValues, props) => {
  // naturally you do something else here if the value
  // used to determine whether this field is required or
  // not is not managed by the same redux form
  const isRequired = allValues.commentRequired === 'Yes'

  if (isRequired && !value) return "Can't be empty."
}

<Field
  name={`${fieldId}.comment`}
  validate={ validateComment }
  label={condition.label}
  className="form-control"
  component={renderTextField}
/>

Hope this helps!

like image 119
jakee Avatar answered Feb 05 '23 16:02

jakee