Bryan
Bryan

Reputation: 1241

Limit Number using Javascript or RegEx

can anyone help me on how could I do on javascript or regEx to limit whole number into 12 with 2 decimal places so that inputs on textbox will be validated?

E.G

999999999999.99 - valid
99999999.999 - invalid
1234584.58 -valid
1.99 - valid
1000000000000 - invalid

Upvotes: 1

Views: 2107

Answers (4)

Ood
Ood

Reputation: 1805

No need for regex.

function check(string){

var list = string.split('.');

if(parseInt(string[0], 10) > 0 && parseInt(string[1], 10) > 0){
if(list.length != 2){
    return false;
}
else if(list[0].length <= 12 && list[1].length <= 2){
    return true;
}
else{
return false;
}
} else{
return false;
}
}

if(check(1000000000000) == true){
    alert('valid');
}
else{
    alert('invalid');
}

I didn't test it, but it should work.

Upvotes: 0

Bryan
Bryan

Reputation: 1241

I've got it and it works perfectly. the below is the regex and the test data

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

123456789123.12 - okay
958.1 - okay
1578463499915 - not (13 numbers)
1548745654485.125 - not (13 numbers and 3 decimals)
5487564.325 - not (3 decimals)
54843. - not (will also validated because no decimal number but have decimal point
112457844.12 - okay
12.12 - okay
512.00 - okay
25867s56.5 - not (have letter)
654.01 - okay
1 - okay
01 - okay
00048 - okay

Upvotes: 0

Stphane
Stphane

Reputation: 3456

The one given is wrong : it wont validate 12 digits

^[0-9]{1,12}\.[0-9]{2}$

1920304049.09 // OK
192030404985  // not ok
1.34          // ok
33.98         // ok
33.9          // not ok

The following will

^(\d{1,12})(\.\d\d)?$

1920304049.09 // OK
192030404985  // ok
1.34          // ok
33.98         // ok
33.9          // not ok

Upvotes: 1

codaddict
codaddict

Reputation: 455322

You can use the regex;

^[0-9]{1,12}\.[0-9]{2}$

Upvotes: 5

Related Questions