1
votes

I have the follow Yup configuration in my React app:

 const schema = yup.object().shape({
        email: yup.string()
            .email('E-mail is not valid!')
            .required('E-mail is required!'),
        password: yup.string()
            .min(6, 'Password has to be longer than 6 characters!')
            .required('Password is required!'),
        tandc: yup.boolean()
            .oneOf([true], "You must accept the terms and conditions")
    })

My form looks like this (using Formik):

 <Form>
                    <div className="form-group">
                        <label >Email
                        <Field type="email" name="email" className="form-control" />
                        </label>
                        <ErrorMessage name="email" component="div" className="invalid-feedback" />
                    </div>
                    <div className="form-group">
                        <label >Password
                        <Field type="password" name="password" className="form-control"  />
                        </label>
                        <ErrorMessage name="password" component="div" className="invalid-feedback" />
                    </div>
                    <div className="form-group">

                        <Field type="checkbox" name="tandc" className="form-check-input"  id="tandc" />
                        <ErrorMessage name="tandc" component="div" className="invalid-feedback" />
                        <label htmlFor="tandc" >I agree to the Terms and Conditions
                        </label>
                    </div>

                    <PrimaryButton label="Login" disabled={isSubmitting} type="submit">
                        Submit
                    </PrimaryButton>
                </Form>

If the user clicks submit on the form, Yup validates the email and password field but ignores the checkbox field:

enter image description here

I can only get the checkbox validation to work if I first check and then uncheck the terms and conditions.

How do I make it work so that it shows the error message when the user clicks just the submit button?

2
.required, I guess? - Gennady Dogaev
I tried required and it made no difference - Michael Edwards
This comment says "if you're using it with formik make sure you set initialValues = {termsOfService: false}" - Gennady Dogaev
@GennadyDogaev you are correct. I need to set an initial value, add it as an answer and I will mark it. - Michael Edwards

2 Answers

2
votes

According to this issue in Yup repository,

if you're using it with formik make sure you set initialValues = {termsOfService: false}

3
votes

For

yup.boolean().oneOf([true],'Message');

to work you have to set the initial value of that field to true or false.

In your case it would look something like this

tandc : false

wherever you are setting the initial values