admin 管理员组文章数量: 1086019
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) )
)
in this case length min 2 and max 10 works, but when is empty is marked with error i tried with val.length == 0
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) )
)
in this case length min 2 and max 10 works, but when is empty is marked with error i tried with val.length == 0
- I guess if you want to allow the value to be empty (0) remove val.length ==0 from code. – Mohit Kushwaha Commented Dec 30, 2021 at 11:20
- add required() after string, will fix the issue – Tigran Petrosyan Commented Dec 30, 2021 at 11:20
- @TigranPetrosyan it mus to allow empty – Alex Commented Dec 30, 2021 at 11:22
-
1
Could it be that
val
beesundefined
if no text is entered? – Peter B Commented Dec 30, 2021 at 11:24 - @PeterB yeah, that was the issue :) – Alex Commented Dec 30, 2021 at 11:27
3 Answers
Reset to default 4Hello you can do it like this
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));
fixed by separate undefined check
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)))
}
),
Global Function,
export const minLengthValidation = (value: string | undefined, limit: number | undefined = 3) => {
if (value && value.length < limit) {
return false
}
return true
}
Invoked the function,
nick_name: yup
.string()
.max(50, 'Nickname must be less than 50 characters!')
.test('min-length', 'Nickname must be greater than 3 characters!', value => minLengthValidation(value))
.required('Nickname is required.'),
本文标签:
版权声明:本文标题:javascript - How to validate using yup to check string min length, max length and allow empty - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744002586a2516718.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论