Published: February 07 2023

React Hook Form 7 - Date Validation Example in React

Example built with React Hook Form 7.43 and React 18.2

This is a quick example of how to validate a date input field in React with React Hook Form. For a more detailed registration form example that includes a bunch of other fields see React Hook Form 7 - Form Validation Example.

Here it is in action: (See on StackBlitz at https://stackblitz.com/edit/react-hook-form-7-date-validation-example)


React Hook Form Component with Date Validation

The app component contains an example form built with the React Hook Form library that contains a single date input field (dob). The field has a required validator and a matches validator, the matches validator is passed a regular expression to test that the input field contains a valid date in the format YYYY-MM-DD

Form validation rules are defined with the Yup schema validation library and passed with the formOptions to the React Hook Form useForm() function, for more info on Yup see https://github.com/jquense/yup.

Displayed date is different from value

The regex pattern is different to the format of the displayed date, the displayed date is formatted based on the browser locale of the user, but the actual value of the input is always in the format yyyy-mm-dd. For more info on the html date input element see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date.

The onSubmit() method is called when the form is valid and submitted, and simply displays the form data in a javascript alert.

import React from 'react';
import { useForm } from "react-hook-form";
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';

function App() {
    // form validation rules 
    const validationSchema = Yup.object().shape({
        dob: Yup.string()
            .required('Date of Birth is required')
            .matches(/^\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/, 'Date of Birth must be a valid date in the format YYYY-MM-DD')
    });
    const formOptions = { resolver: yupResolver(validationSchema) };

    // get functions to build form with useForm() hook
    const { register, handleSubmit, reset, formState } = useForm(formOptions);
    const { errors } = formState;

    function onSubmit(data) {
        // display form data on success
        alert('SUCCESS!! :-)\n\n' + JSON.stringify(data, null, 4));
        return false;
    }

    return (
        <div className="card m-3">
            <h5 className="card-header">React Hook Form 7 - Date Validation</h5>
            <div className="card-body">
                <form onSubmit={handleSubmit(onSubmit)}>
                    <div className="row">
                        <div className="col-6 mb-3">
                            <label class="form-label">Date of Birth</label>
                            <input name="dob" type="date" {...register('dob')} className={`form-control ${errors.dob ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.dob?.message}</div>
                        </div>
                    </div>
                    <div className="form-group">
                        <button type="submit" className="btn btn-primary me-1">Submit</button>
                        <button type="button" onClick={() => reset()} className="btn btn-secondary">Reset</button>
                    </div>
                </form>
            </div>
        </div>
    )
}

export { App };

 


Need Some React Hook Form Help?

Search fiverr for freelance React Hook Form 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