gpt4 book ai didi

javascript - 使用 Backbone.validation 验证多个输入的一条规则

转载 作者:行者123 更新时间:2023-12-03 05:33:14 24 4
gpt4 key购买 nike

例如,我有 10 个输入。我想使用一条规则检查它们是否为空,但避免像这样重复:

firstInput :{
required: true,
msg: 'Empty!'
},
// ...

tenthInput :{
required: true,
msg: 'Empty!'
}

是否有任何方法可以使用 Backbone Validation 对所有输入使用一个规则?并且每个输入可以同时具有其他唯一的验证规则,例如:

firstInput :{
pattern: email,
msg: 'Email!!!'
}

最佳答案

来自Backbone Validation documentation :

// validation attribute can also be defined as a function returning a hash
var SomeModel = Backbone.Model.extend({
validation: function() {
return {
name: {
required: true
}
}
}
});

然后您可以调整模型以使其具有以下功能:

var SomeModel = Backbone.Model.extend({
/**
* List of field which are required.
* @type {Array|Function}
*/
required: ['firstInput', 'secondInput', /*...*/ 'tenthInput'],
/**
* Same format as Backbone Validation
* @type {Object|Function}
*/
specificValidation: {
firstInput: {
pattern: "email",
msg: 'Email!!!'
}
},

validation: function() {
var inputs = _.result(this, 'required'),
rules = _.result(this, 'specificValidation'),
requiredRule = { required: true, msg: 'Empty!' };

// apply the default validation to each listed field
// only if not already defined.
_.each(inputs, function(field) {
rules[field] = _.defaults({}, rules[field], requiredRule);
});

return rules;
}
});

关于javascript - 使用 Backbone.validation 验证多个输入的一条规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40845189/

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