给定以下主干形式架构片段:
number_of_products: {
type: "Text",
title: "Number of products",
validators: ["required", "integer"]
},
我将如何定义验证器属性以将输入限制在 和 之间的13
值42
?
给定以下主干形式架构片段:
number_of_products: {
type: "Text",
title: "Number of products",
validators: ["required", "integer"]
},
我将如何定义验证器属性以将输入限制在 和 之间的13
值42
?
我认为创建一个验证器更可重用:
// 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
}]
}
首先,您可以更改type
toNumber
然后添加验证功能:
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)]
}