gpt4 book ai didi

javascript - 测试单个值时 validate.js 返回未定义

转载 作者:行者123 更新时间:2023-11-27 22:35:07 25 4
gpt4 key购买 nike

我正在尝试使用 validate.js 来验证单个值库,但我从 validate.single() 函数获取 udefine 结果。

var test1 = "test12345";
var test2 = "1234";
var test3 = "";

var constraints1 = {
length: {
is: 4
}
}

var constraints2 = {
length: {
minimum: 4
}
}

var constraints3 = {
length: {
maximum: 4
}
}

console.log('Testing for exact length');
console.log(validate.single(test1, constraints1));
console.log(validate.single(test2, constraints1));
console.log(validate.single(test3, constraints1));

console.log('Testing for min length');
console.log(validate.single(test1, constraints2));
console.log(validate.single(test2, constraints2));
console.log(validate.single(test3, constraints2));

console.log('Testing for max length');
console.log(validate.single(test1, constraints3));
console.log(validate.single(test2, constraints3));
console.log(validate.single(test3, constraints3));

以上示例的结果:

[Log] Testing for exact length
[Log] ["is the wrong length (should be 4 characters)"]
[Log] undefined
[Log] undefined
[Log] Testing for min length
[Log] undefined
[Log] undefined
[Log] undefined
[Log] Testing for max length
[Log] ["is too long (maximum is 4 characters)"]
[Log] undefined
[Log] undefined

为什么未定义?

JSFiddle:https://jsfiddle.net/3s8ckdkc/13/

最佳答案

请查看您正在使用的图书馆的主页。

在示例中,有一个 pass 情况表明返回未定义

简而言之,如果约束被破坏,库就会返回一个值。

否则返回未定义

库将空、null 或未定义视为有效值。

来自页面:

Important! One thing that is a bit unorthodox is that most validators will consider empty values (null, undefined, whitespace only strings etc) valid values. So for example adding a constraint of at least 6 characters will be like saying If the attribute is given it must be at least 6 characters. This differs from example Ruby on Rails where validators instead have the allow_nil option. I find it quite common that you want to have constraints on an optional attribute.

这意味着您放置空字符串的 test3 始终有效,因为它是空字符串,与您的约束无关。

关于javascript - 测试单个值时 validate.js 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39178925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com