I'm currently working on Regular Expression to check the decimal input in JavaScript. Below are the mock-up test case:
HTML:
<input type="text" id="checkValue" onkeypress="checkKey(event)"/>
JavaScript:
function checkKey(event) {
if(event.which == '13') { //Enter is pressed
var checkVal = $('#checkValue').val().trim();
if(checkVal.match("(\d{1,7}\.\d{1,2})|(\.\d{1,2})|(0)")) {
alert("Matched!");
} else {
alert("Not matched!");
}
}
}
Supposed I type in "123.456" will return "Not matched!", but it returns "Matched!".
The desired result would be:
Match type:
.01
1
1.01
0
1234567.89
Unmatch type:
.012
1.098
123.456
As conclusion, the value input should be in 9 digits at most, with or without decimal. And id with decimal, it only takes 2 places, such as "1234567.89".
It's my first time stepping in Regex, so any advice in getting this well?
Any help in helping fixing the Regex above would be great :)
Edited
function checkKey(event) {
if(event.which == '13') { //Enter is pressed
var checkVal = $('#checkValue').val().trim();
alert(checkVal.match(/^\d{0,7}\.?\d{0,2}|\.\d{0,2}|0$/));
}
}
Same, the input I typed "123.456", but the alert message I get was "123.45"...
Second edit
function checkKey(event) {
if(event.which == '13') { //Enter is pressed
var checkVal = $('#checkValue').val().trim();
alert(checkVal.match(/^\d{0,7}(\.\d{0,2}|\d{0,2})$/g));
}
}
I've changed from
/^\d{0,7}(\.\d{0,2}|\d{0,2})$/g
to
/^\d{0,7}\.?\d{0,2}$/g
, which is simplified :)
And it works for numbers, but how if I would like when user key in only "." and is not acceptable? Also, zero as starting is not acceptable as well. Do I need to separate into 2 regex checking?