给出以下骨干表单模式片段:
number_of_products: {
type: "Text",
title: "Number of products",
validators: ["required", "integer"]
},
如何定义验证器属性以限制13
和42
之间的值的输入?
答案 0 :(得分:2)
首先,您可以将type
更改为Number
,然后添加验证功能:
function validateNumber(min, max) {
return function(val) {
if (val < min || val > max) {
return {
type: 'invalid number',
message: 'Must be between '+min+' and '+max+'.'
};
}
};
}
...
number_of_products: {
type: "Number",
title: "Number of products",
validators: ["required", validateNumber(13, 42)]
}
答案 1 :(得分:2)
我认为创建验证器更具有可再利用性:
// interval validator
BackBoneForms.validators.interval = function(options) {
// get the min value
var minValue = parseFloat(options.min) || 0;
var maxValue = parseFloat(options.max) || 0;
var err = {
type: options.type,
message: "value must between "+minValue+" and "+maxValue
};
return function interval(value, attrs) {
var fieldValue = 0;
if (value === null || value === undefined || value === '') return err;
// check if the value is number
if( !isNaN(parseFloat(value)) && isFinite(value)) {
fieldValue = parseFloat(value);
}
if( minValue > fieldValue || maxValue < fieldValue ) {
return err;
}
return ;
}
}
您可以将其用作:
number_of_products: {
type: "Number",
title: "Number of products",
validators: ["required", {
type : "interval" ,
max : 10,
min : 0
}]
}