Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux Form Checkbox Validation

I have the following code. The checkbox is for confirming that the user has read Terms and Conditions. Im not sure how to add validation for this on the front end. i.e. If the user clicks submit without checking this box, I want to highlight this text in some way that lets the user know to agree to Terms.

<Field
    label='Terms'
    name="terms-and-conditions"
    type="checkbox"
    component={this.renderField}
    submissionErrors={this.state.submissionErrors}
/>
like image 711
Rahul Ramesh Avatar asked Mar 08 '23 14:03

Rahul Ramesh


1 Answers

You can create a custom component for the Field component. In the custom component you will receive error prop so you can process with additional styling, error messages, etc. If you want to validate on submit, pass onSubmit prop to the decorated component.

Live example: https://codesandbox.io/s/207mj8k3py

Create a custom component with the error logic:

const Checkbox = ({ input, meta: { touched, error } }) => (
  <div style={{ border: touched && error ? "1px solid red" : "none" }}>
    <input type="checkbox" {...input} />
    <label>Terms and conditions</label>
  </div>
)

Set Field's component prop to Checkbox:

const SimpleForm = ({ handleSubmit, onSubmit }) => (
  <form onSubmit={handleSubmit(onSubmit)}>
    <Field
      name="termsAndConditions"
      component={Checkbox}
    />
    <div>
      <button type="submit">Submit</button>
    </div>
  </form>
)

In onSubmit function, check if the checkbox is checked, if not - throw SubmissionError with the name of the Field:

const onSubmit = values => {
  if (!values.termsAndConditions) {
    throw new SubmissionError({ 
      termsAndConditions: 'Field required' 
    })
  }

  console.log('Form submitted')
}

Decorate the form:

export default reduxForm({
  form: "simple",
  onSubmit
})(SimpleForm)
like image 126
morganfree Avatar answered Mar 16 '23 23:03

morganfree