[英]Yup is not validating a checkbox when the user clicks the submit button
我的 React 應用程序中有以下 Yup 配置:
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")
})
我的表格看起來像這樣(使用 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>
如果用戶在表單上單擊提交,Yup 會驗證 email 和密碼字段但忽略復選框字段:
如果我先選中然后取消選中條款和條件,我只能讓復選框驗證工作。
我如何讓它工作,以便在用戶僅單擊提交按鈕時顯示錯誤消息?
根據 Yup 存儲庫中的這個問題,
如果您將它與 formik 一起使用,請確保設置
initialValues = {termsOfService: false}
為了
yup.boolean().oneOf([true],'Message');
要工作,您必須將該字段的初始值設置為true
或false
。
在你的情況下,它看起來像這樣
tandc : false
無論您在哪里設置初始值
如果您使用的是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")
})
學分: 傑森·沃特莫爾
用
yup.default(false)
或者
yup.default(true)
指定默認值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.