In this article, we will learn how to make todate and fromdate validation using YUP react js.
First, we have to install yup npm using the below command
npm i yup
Then install react-hook-form using below command
npm i react-hook-form
Then using useform we have created a form and created a todate and fromdate fields, you can see below the code
<form className="input_form" onSubmit={handleSubmit(submitHandler)} > <div className="col-md-4"> <div className="form-group mb-15"> <label>From Datetime</label> <input type="date" className="form-control datetimepicker date-form-control" id="fromDateTime" placeholder="mm/dd/yyyy" // ref={ref} {...register("fromDateTime")} /> <small className="form-text" style={{ color: 'red' }}>{errors.fromDateTime ? errors.fromDateTime.message : ''}</small> </div> </div> <div className="col-md-4"> <div className="form-group mb-15"> <label>To Datetime</label> <input type="date" className="form-control datetimepicker date-form-control" id="toDateTime" placeholder="mm/dd/yyyy" // onChange={() => reset()} {...register("toDateTime")} /> <small className="form-text" style={{ color: 'red' }}>{errors.toDateTime ? errors.toDateTime.message : ''}</small> </div> </div> </form>
Then install yup resolver using below command
npm i @hookform/resolvers
use yup like this and use below code for todate and from date ref validation
const { register, handleSubmit, formState: { errors }, control, ref, reset } = useForm({ resolver: yupResolver(yup.object().shape({ fromDateTime: yup.date().max(new Date(), "Future date not allowed").typeError("Invalid From date"), toDateTime: yup.date().min( yup.ref('fromDateTime'), "To date can't be before from date" ).required('From is required').max(new Date(), "Future date not allowed").typeError("Invalid To date"), comFromDateTime: yup.date().max(new Date(), "Future date not allowed").typeError("Invalid From date"), comToDateTime: yup.date().min( yup.ref('comFromDateTime'), "To date can't be before from date" ).max(new Date(), "Future date not allowed").typeError("Invalid To date") })) })
you can see output below, how its work