1
votes

I have text fields and need to do validation for it. Here is my code example:

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>

}

What is the best way to do validation using react? I read about formik and yup, but I found that in my case, yup isn't effiecient way. Maybe anyone could suggest the best solution for ex. for email? Sorry, I'm new in fronted, so I don't know much.

2
check my answer below.Hadi Pawar

2 Answers

0
votes

Formik is the best way to go in my opinion. npm install --save formik Then in your code :

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>
);

}
0
votes

You can use yups default scheme:

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

Or use your custom:

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'),
})