javascript 验证使用 Yup 来检查字符串或数字长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49886881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validation using Yup to check string or number length
提问by reectrix
Is there a yup function that validates a specific length?
是否有验证特定长度的 yup 函数?
I tried .min(5)and .max(5), but I want something that ensures the number is exactly 5 characters (ie, zip code).
我试过.min(5)and .max(5),但我想要确保数字正好是 5 个字符(即邮政编码)的东西。
采纳答案by Tamlyn
I don't think there's anything built in but it's easy to implement with test:
我认为没有内置任何东西,但很容易实现test:
yup.string()
.test('len', 'Must be exactly 5 characters', val => val.length === 5)
回答by efru
For future reference, if you're looking to validate a number (zip code), the above solution requires a slight tweak. The function should be :
为了将来参考,如果您要验证数字(邮政编码),上述解决方案需要稍作调整。功能应该是:
Yup.number().test('len', 'Must be exactly 5 characters', val => val.toString().length === 5)
Yup.number().test('len', 'Must be exactly 5 characters', val => val.toString().length === 5)
.lengthdoes not work on numbers, only strings.
.length不适用于数字,仅适用于字符串。
回答by dtesta
@Tamlyn's answercovers the length validation aspect of the question quite well.
@Tamlyn 的回答很好地涵盖了问题的长度验证方面。
In the case of a zip code, you could use a regexto enforce the length and limit to numeral values within the Yup.string()(you wouldn't want to use a Yup.number()type as it wouldn't support zip codes starting with a zero 0####)
在邮政编码的情况下,您可以使用正则表达式来强制长度和限制数字值Yup.string()(您不想使用Yup.number()类型,因为它不支持以零开头的邮政编码0####)
// ##### format zip code
Yup.string().matches(/^[0-9]{5}$/, 'Must be exactly 5 digits')
// ##### and #####-#### format zip codes
Yup.string().matches(/^[0-9]{5}(?:-[0-9]{4})?$/, 'Must be 5 or 9 digits')
回答by David Ferreira
You can also use string.length.
您也可以使用string.length.
yup.string().length(5)
But it doesn't work with numbers starting with zeros:
但它不适用于以零开头的数字:
const yup = require('yup')
const schema = yup.string().length(5)
console.log(schema.isValidSync(12345)) // (true) This is valid.
console.log(schema.isValidSync(00123)) // (false) This is NOT valid.
回答by SimoAmi
This check leads to the best validation experience:
此检查可带来最佳验证体验:
Yup.string()
.required()
.matches(/^[0-9]+$/, "Must be only digits")
.min(5, 'Must be exactly 5 digits')
.max(5, 'Must be exactly 5 digits')
output:
输出:
12f1 // Must be only digits
123 // Must be exactly 5 digits
123456 // Must be exactly 5 digits
01234 // valid
11106 // valid
回答by BoyePanthera
The test API runs into issues with ReactJs when your field has no value. You can use the length API instead
当您的字段没有值时,测试 API 会遇到 ReactJs 问题。您可以改用长度 API
Yup.string().length(4, 'This field has to be exactly 4 characters!')
回答by Matt Royal
To add to the other answers, none of them are checking that a value exists (I see some have mentioned this in comments after posting this though)...
要添加到其他答案中,他们都没有检查值是否存在(我看到有些人在发布此内容后在评论中提到了这一点)...
If it is not present and the field is left empty, it will be trying to get the length of undefinedor nullwhich will then give you a javascript error and prevent other conditions such as .required()from working (if you had it setup like of course).
如果它不存在并且该字段留空,它将尝试获取undefined或的长度,null然后会给你一个javascript错误并阻止其他条件,例如.required()工作(如果你像当然一样设置了它)。
This would probably be slightly better:
这可能会稍微好一点:
// Check we have a value as well
Yup.number().test('len', 'Must be exactly 5 characters', val => val && val.toString().length === 5 )
回答by tschumann
@efru's answerworks great for numbers that are less than 22 characters. However val.toString().lengthdoes not work for numbers larger than 22 characters. The reason for this is that larger numbers are converted to exponential format when converted to a string in javascript.
@efru 的答案适用于少于 22 个字符的数字。但是val.toString().length不适用于大于 22 个字符的数字。这样做的原因是较大的数字在 javascript 中转换为字符串时会转换为指数格式。
The solution I found that works best is:
我发现最有效的解决方案是:
Yup.number().test('len', 'Must be exactly 25 characters', val => Math.ceil(Math.log10(val + 1)) === 25)
Yup.number().test('len', '必须正好是 25 个字符', val => Math.ceil(Math.log10(val + 1)) === 25)
回答by s.hesam
Your way is the correct way and simplest.
你的方法是正确的,也是最简单的。
Yup.string()
.required()
.min(5, 'Must be exactly 5 digits')
.max(5, 'Must be exactly 5 digits')

