javascript

Apply multiple validation on same field redux form

You can pass validators functions inside validate attribute of redux-form Field to apply multiple validations on the same Field.

const requiredValidator = (value) => (value ? undefined : "This field is required");
const maxLengthValidator = (max) => (value) =>
  value && value.length > max ? `Field sust be ${max} characters or less` : undefined;
const inputMaxLength = maxLengthValidator(10);

<Field
    name="firstName"
    type="text"
    component={renderField}
    label="Fiest Name"
    validate={[requiredValidator, inputMaxLength]}
/>

We can apply multiple validations on the same field when creating the form using Redux Form. The Field which is imported from redux-form has an attribute 'validate' which can accept function name that has rules to validate the particular field. It can also take multiple function names in array format.

In the code snippet, we are adding a required field validator and maximum length validator on the field firstName.

We have created two validators - requiredValidator which will validate if the input text is not empty and inputMaxLength which will validate if the input text does not exceed the maximum length that we defined. Here we have defined the maximum length to 20.

The Full Example is as below:

import React from "react";
import { Field, reduxForm } from "redux-form";

const requiredValidator = (value) => (value ? undefined : "This field is required");
const maxLengthValidator = (max) => (value) =>
  value && value.length > max ? `Field sust be ${max} characters or less` : undefined;
const inputMaxLength = maxLengthValidator(10);

const renderField = ({input, label, type, meta: { touched, error, warning } }) => (
  <div>
    <label>{label}</label>
    <div>
      <input {...input} placeholder={label} type={type} />
      {touched &&
        ((error && <span>{error}</span>) ||
          (warning && <span>{warning}</span>))}
    </div>
  </div>
);

const MultiValidationForm = (props) => {
  const { handleSubmit, pristine, reset, submitting } = props;
  return (
    <form onSubmit={handleSubmit}>
      <Field
        name="username"
        type="text"
        component={renderField}
        label="Username"
        validate={[requiredValidator, inputMaxLength]}
      />
      <div>
        <button type="submit" disabled={submitting}>
          Submit
        </button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>
          Clear Values
        </button>
      </div>
    </form>
  );
};

export default reduxForm({
  form: "MultiValidationForm"
})(MultiValidationForm);
Was this helpful?