文本字段验证。反应:formik,是

时间:2020-04-15 13:17:56

标签: validation formik yup

我有文本字段,需要对其进行验证。这是我的代码示例:

export default function UserInformation() {

<form className={classes.root} autoComplete="off">
   <div>
       <div>
            <TextField
              className={classes.textField}
              required
              id="Email"
              label="Email"
              defaultValue=""
            />
       </div>
   </div>
</form>

}

使用react进行验证的最佳方法是什么?我阅读了有关formik和yup的文章,但我发现以yup的方式行之有效。也许任何人都可以为ex建议最佳解决方案。接收电子邮件? 抱歉,我是新来的,所以我了解不多。

2 个答案:

答案 0 :(得分:0)

Formik是我认为最好的方法。 npm install --save formik 然后在您的代码中:

import {useFormik} from "formik";

//Has all the validations it is very flexible so edit according to your need.
const validate = values => {
    const errors = {};

    if (!values.password) {
        errors.password = 'Required';
    } else if (!(values.password.length >= 8 && values.password.length < 200)) {
        errors.password = 'Must be greater then 8 characters and less then 200 ';
    }

    if (!values.email) {
        errors.email = 'Required';
    } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
        errors.email = 'Invalid email address';
    }

    return errors;
};

export default function UserInformation() {

//Initialize formik with default values 
 const formik = useFormik({
        initialValues: {
            email: '',
            password: ''
        },
        validate,
       //Called after you click on Submit button below
        onSubmit: values => {
             //DO somthing with values
           }
    });

return(
<form onSubmit={formik.handleSubmit} className={classes.root} autoComplete="off">
   <div>
       <div>
            <TextField
              className={classes.textField}
              required
              id="email"
              name="email"
              label="email"
              defaultValue=""
              //These methods are for validation and handling change.
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              value={formik.values.email}
            />
             //Any errors of validation will be displayed here use any alert component you like
             {formik.touched.email && formik.errors.email ? (
                                    <MDBAlert color="danger" >
                                        {formik.errors.email}
                                    </MDBAlert>
                                ) : null}
       </div>
   </div>
 <button type="submit">Done</button>
</form>
);

}

答案 1 :(得分:0)

您可以使用yups默认方案:

Yup.object().shape({
 email: Yup.string()
            .email('Invalid email!')
            .required('Please, enter email'),
})

或使用您的自定义:

Yup.object().shape({
 email: Yup.string()
            .matches(
            /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/, // or any other regex
            'Enter correct email'
        )
        .required('Please, enter phone'),
})