'Yup is not validating a checkbox when the user clicks the submit button
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:
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?
Solution 1:[1]
According to this issue in Yup repository,
if you're using it with formik make sure you set
initialValues = {termsOfService: false}
Solution 2:[2]
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
Solution 3:[3]
Use
yup.default(false)
or
yup.default(true)
to specify default value
Solution 4:[4]
If you are using react-hook-form:
const schema = yup.object().shape({
...
tandc: yup.bool() // use bool instead of boolean
.oneOf([true], "You must accept the terms and
conditions")
})
credits: Jason Watmore
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gennady Dogaev |
| Solution 2 | Artan M. |
| Solution 3 | Stephen Ostermiller |
| Solution 4 | Isaac Pak |

