[英]How to validate using yup to check string min length, max length and allow empty
firstName: yup
.string()
.test(
'len',
'can be empty or with string at least 2 characters and not more than 10',
(val) => val != undefined && (val.length == 0 || (val.length >= 2 && val.length <= 10) )
)
在這種情況下,長度 min 2 和 max 10 有效,但是當為空時標記為錯誤我嘗試使用val.length == 0
通過單獨的未定義檢查修復
firstName: yup
.string()
.test(
'len',
'can be empty or with string at least 2 characters and not more than 10',
(val) => {
if (val == undefined) {
return true;
}
return ((val.length == 0 || (val.length >= 2 && val.length <= 10)))
}
),
你好你可以這樣做
const yup = require("yup"); const firstName = ""; const schema = yup.string().test( "len", "can be empty or with string at least 2 characters and not more than 10", (val) => { if (val === undefined) { return true; } return val.length === 0 || (val.length >= 2 && val.length <= 10); } ); schema.validate(firstName).then((response) => console.log(response)).catch((err) => console.log(err));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.