如何在主干形式的整数文本字段上定义最小/最大验证



给定以下主干表单架构片段:

number_of_products: {
  type: "Text",
  title: "Number of products",
  validators: ["required", "integer"]
},

我将如何定义验证器属性以将输入限制为 1342 之间的值?

首先,

您可以将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)]
}

我认为创建一个验证器更可重用:

// 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
 }]

}

相关内容

  • 没有找到相关文章

最新更新