只允许 6 位数字或 2 位小数的 8 位数字

Only allow 6 digit number or 8 digit number with 2 decimal places

我创建了一个验证器来检查数字是否为数字并确保小数点后允许有 2 位数字。这不包括一个没有小数位的 6 位数字 (123456) 或有 2 位小数的 8 位数字 (123456.78)。这是我想出的

function validateInt2Dec(value, min, max) {

    if (Math.sign(value) === -1) {
        var negativeValue = true;
        value = -value
    }

    if (!value) {
        return true;
    }
    var format = /^\d+\.?\d{0,2}$/.test(value);
    if (format) {
        if (value < min || value > max) {
            format = false;
        }
    }
    return format;
}

及其形式的实现

     vm.fields = [
             {
                className: 'row',
                fieldGroup: [
                    {
                        className: 'col-xs-6',
                        key: 'payment',
                        type: 'input',
                        templateOptions: {
                            label: 'Payment',
                            required: false,
                            maxlength: 8
                        },
                        validators: {
                            cost: function(viewValue, modelValue, scope) {
                                var value = modelValue || viewValue;
                                return validateInt2Dec(value);
                            }
                        }
                    }
                ]
            }
        ];

我必须添加什么才能涵盖上述情况?

在 regex101 上试试这个似乎符合你的标准。

解决方案:^(\d{6})?(\d{8}\.\d{2})?$

  • 第 1 组 ^(\d{6})?- 任意 6 位数字

  • 第 2 组 ^(\d{6})?(\d{8}\.\d{2})?$ - 或带 2 个小数位的 8 位数字

如果您不想增加额外的正则表达式复杂性,您可以做的是在最终通过之前对 maxLength 进行额外检查

var str = value.toFixed(2);
var maxLength = (str.indexOf(".") > -1 ? 8 : 6);
if (str.length > maxLength) {
    return; //invalid input
}

试试下面的正则表达式。

var regex = /^\d{1,6}(\.\d{1,2})?$/;

console.log(regex.test("123456"));
console.log(regex.test("123456.78"));
console.log(regex.test("123456.00"));
console.log(regex.test("12345.00"));
console.log(regex.test("12345.0"));
console.log(regex.test("12345.6"));
console.log(regex.test("12.34"));
console.log(regex.test("123456.789"));