Search code examples
javascriptangularjsvalidationangular-formly

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. 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). 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?


Solution

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