Published: February 08 2020

React + Formik - Required Checkbox Example

Example built with React 16.12 and Formik 2.1.4

Other versions available:

This is a quick example of how to implement a required checkbox field in React with Formik using the Yup object schema validator.

Here it is in action: (See on StackBlitz at https://stackblitz.com/edit/react-formik-required-checkbox)


React + Formik Required Checkbox App Component

The app component contains an example form built with Formik that contains a single "Accept Terms & Conditions" checkbox field that is required.

The checkbox is set to required with the schema rule acceptTerms: Yup.bool().oneOf([true], 'Accept Terms & Conditions is required') and by setting the initial value acceptTerms: false inside initialValues.

import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';

class App extends React.Component {
    render() {
        return (
            <Formik
                initialValues={{
                    acceptTerms: false
                }}
                validationSchema={Yup.object().shape({
                    acceptTerms: Yup.bool().oneOf([true], 'Accept Terms & Conditions is required')
                })}
                onSubmit={fields => {
                    alert('SUCCESS!! :-)\n\n' + JSON.stringify(fields, null, 4))
                }}
            >
                {({ errors, status, touched }) => (
                    <Form>
                        <div className="form-group form-check">
                            <Field type="checkbox" name="acceptTerms" className={'form-check-input ' + (errors.acceptTerms && touched.acceptTerms ? ' is-invalid' : '')} />
                            <label htmlFor="acceptTerms" className="form-check-label">Accept Terms & Conditions</label>
                            <ErrorMessage name="acceptTerms" component="div" className="invalid-feedback" />
                        </div>
                        <div className="form-group">
                            <button type="submit" className="btn btn-primary mr-2">Submit</button>
                            <button type="reset" className="btn btn-secondary">Reset</button>
                        </div>
                    </Form>
                )}
            </Formik>
        )
    }
}

export { App }; 

For a more detailed Formik validation example that includes a registration form with this required checkbox as well as a bunch of other fields see React + Formik 2 - Form Validation Example.

 


Need Some React Help?

Search fiverr for freelance React developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by