CodeGeek
CodeGeek

Reputation: 3

How to format number in JavaScript

I need to do dynamic validation on a number while user giving input. Number format should be-- before decimal it should restrict 12 digit and after decimal 2 digit. I have written one validation function using Onkeyup and by giving maxlength. But I am facing issue like, if I remove one digit after decimal then its allowing more than 13 digit before decimal.

below function I have written for validation

function validation(e){
    var t = e.value;
    if( t.indexOf(".") <= 0 ) {
        e.value = t.substr(0,12);
    }
    if( ( t.slice( 0, e.selectionStart ).length >= ( t.indexOf(".") + 3 ) ) {
        
        e.value = ( t.indexOf(".") >= 0 ) ? 
            ( t.substr( 0, t.indexOf(".") ) + t.substr( t.indexOf("."), 3 ) ) :
            t
}

Appreciate any help!! Thanks.

Upvotes: 0

Views: 478

Answers (1)

michaelT
michaelT

Reputation: 1711

Regex

You can use a regular expression (regex). For instance:

^(([1-9]{1}[0-9]{0,11}|[0-9]{1}))(\.\d{1,2})?$

Ok let's check out:

Numbers before the decimal point: ([1-9]{1}[0-9]{0,11}|[0-9]{1}) So either [1-9]{1}[0-9]{0,11} or [0-9]{1}, where the first expression prevents leading zeros and second expression makes the input o f 0 possible.

These expressions are followed by an optional decimal point (\.\d{1,2})?. The ? means that the expression can be there 0 or 1 times (so the input can be a decimal number or not). After the decimal point there have to be one 1 or 2 numbers (decimals).

You can try the expressions here: Online regex tester and debugger. This should work:

123456789123
123.40
0
0.0
953
953.1
953.0
953.01
953.12

This should not work:

1234567891239 // 13 numbers
000.12 // leading zeros
123.001 // Too many decimals

Implementation

Possibility 1 is to insert the regex directly into the <input> using the pattern attribute. Possibility 2 is to do the validation via javascript. Note that you have to escape the backslashes \\.

let pattern = '^(([1-9]{1}[0-9]{0,11}|[0-9]{1}))(\\.\\d{1,2})?$';
let regex = new Regex(pattern);

function validation(e){
    if(regex.test(e.value)){
        // Value fits the pattern
    }else{
        // Value do not fit the pattern
    }
}

Upvotes: 1

Related Questions