简体   繁体   English

仅允许使用6位数字或8位数字,小数点后两位

[英]Only allow 6 digit number or 8 digit number with 2 decimal places

I've created a validator that checks if digit is a number and makes sure there are 2 digits allowed after a decimal place. 我已经创建了一个验证器,用于检查数字是否为数字,并确保小数点后允许有2位数字。 What this doesn't cover is a number that is either 6 digits with no decimal places (123456) or 8 digits with 2 decimal places (123456.78). 它不能覆盖的数字是不带小数位的6位数字(123456)或带2个小数位的8位数字(123456.78)。 This is what I came up with 这就是我想出的

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;
}

and its implementation in formly form 及其正式形式的实施

     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);
                            }
                        }
                    }
                ]
            }
        ];

What do I have to add to cover above scenario? 我必须添加什么才能涵盖上述情况?

Try regex below. 在下面尝试正则表达式。

 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")); 

Trying this out on regex101 seems to fit you criteria. 在regex101上进行尝试似乎符合您的标准。

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

  • Group 1 ^(\\d{6})? 第1组^(\\d{6})? - either 6 digits -6位数字

  • Group 2 ^(\\d{6})?(\\d{8}\\.\\d{2})?$ - or 8 digits with 2 decimal place 组2 ^(\\d{6})?(\\d{8}\\.\\d{2})?$ -或8位小数点后两位

If you don't want to add additional regex complexity, what you can do is make an additional check of maxLength before finally giving it a pass 如果您不想增加其他正则表达式的复杂性,您可以做的是对maxLength进行额外的检查,然后再最终通过

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM