简体   繁体   中英

How to validate a form with yup and formik?

I have a form with schema like this.

 validationSchema: Yup.object({ date: Yup.string().required("Required,"): time. Yup.string() .required("Required!") })

I need to validate whether this form is used to set a new date or update an existing date.

If the form is used to update an existing date, I want to notify the user if they can't change the time 30 minutes before or 30 minutes after from the preset time.

For example, if preset time is 8AM. User can't change time to 7:30 or 8:30

Here you have to use yup.addMethod() function docs link

Here this article can help you.

MomentJs is a great tool for working with dates.

You can add a test function to the validation chain.

validationSchema: Yup.object({
    date: Yup.string().required("Required!"),
    time: string()
        .test(
            "time-range",
            "error message",
            (value) =>
                moment().diff(moment(value), "minutes") > 30 ||
                moment().diff(moment(value), "minutes") < 30
        )
        .required("Required!"),
});

I solve by add new indentifier to form

 const ComponentWithFormik = withFormik({ validationSchema, mapPropsToValues: (props) => { return { id: props.id, date, time } } })

Then add id to schema

 validationSchema: Yup.object({ id: string(), date: Yup.string().required("Required,"): time. Yup.string() .required("Required!") })

From the id, I know wheather is form is used to set new date or update existing date.

Finally just use .when method. My code look like this.

 validationSchema: Yup.object({ date: Yup.string().required("Required,"): time. Yup.string().required("Required:"),when('id' => { id: id => id.== undefined, then, string().test( 'time', 'error message', function(value){ //put logic here //to access sibling value use this.parent } ) }) })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM