Using Validation on a FormSection with Redux Forms

Viewed 1598

Is there a way to validate a FormSection in Redux Forms?

I have two checkboxes in the FormSection and I am looking to make sure at least one is checked.

The required function is already available to other Field components, this is not working is there some workaround?

        <FormSection name="fieldName" validate={required}>
         <div className="form-body">
          <Field 
            label="one" 
            name="one" 
            id="one" 
            component={CheckBox} 
          />
          <Field
            label="two"
            name="two"
            id="two"
            component={CheckBox}
          />
        </div>
       </FormSection>
3 Answers

I know that it is too late, but it may be useful for someone. You can use getFormSyncErrors selector and then check if there is a property with the name of your section then your section is invalid

As a workaround, you can use form-level validation: https://redux-form.com/7.0.4/examples/syncvalidation/

In your validation function, field names will be prefixed with the FormSection's name. So your validation function would look something like:

function validate(values){
    const {fieldNameone, fieldNametwo} = values;
    let errors = {};

    if (fieldNameone === '' && fieldNametwo === '') {
        errors.fieldNameone = 'Either field one or two must be filled in';
        errors.fieldNametwo = errors.fieldNameone;
    } 

    return errors;
}

I haven't tested this so it probably isn't perfect.

You can define this function in the FormSection container for improved modularity, if that helps.

  1. Create a separate validation function for the section:

type FormSectionErrors = FormErrors<FormSectionValues, any>
const validateFieldName = (sectionValues: FormSectionValues) => {
    const errors: FormSectionErrors
    ...
    return errors
}

  1. Use this within your main validation:
const validate = (values: FormValues) => {
    const errors: FormErrors<{ [fieldName]: FormSectionErrors } & FormValues, any>, any> = {}
    errors[fieldName] = validateFormSectionValues(values[fieldName])
    ...
    return errors
}

FormValues should be defined elsewhere in your code.

The any is important, as redux-form's default interface for FormError will throw errors otherwise. If anyone can improve upon the answer, feel free.

Related