Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Decimal Place Restriction With RegEx

I have some client-side validation against a text box, which only allows numbers up to two decimal places with no other input.

This script was a basis for entering numeric values only, however it needs to be adapted so it can take a decimal point followed by only up to two decimal places.

I've tried things such as /[^\d].\d{0,2}, but then the replacement call wouldn't work, and I've got no idea how to do it.

Code

<script type="text/JavaScript">
  function valid(f) {
    if (!/^\d*$/.test(f.value)) {
      f.value = f.value.replace(/[^\d]/g,"");
      alert("Invalid number");
    }
  }
</script>

Note

I need to match an empty string. If an empty string is provided and the form is submitted, the value defaults back to zero.

like image 257
Kezzer Avatar asked Jan 22 '09 10:01

Kezzer


4 Answers

The . character has special meaning in RegEx so needs escaping.

/^(?:\d*\.\d{1,2}|\d+)$/

This matches 123.45, 123.4, 123 and .2, .24 but not emtpy string, 123., 123.456

like image 112
AnthonyWJones Avatar answered Nov 10 '22 00:11

AnthonyWJones


. means in RegEx: any character, you have to put a backslash infront of it. \.

This would be better:

/^\d+(\.\d{0,2})?$/

Parts I included:

  • You need at least 1 number in front of the dot. If you don't want this, replace + with * but then also empty strings would be matched.
  • If you have decimal values you need the dot in front.
  • There shouldn't be anything after the number, $ stands for the end of the input.

and for the replacing part you should also include the dot

f.value.replace(/[^\d\.]/g, "")

Edit:

If it's for the live validation of inputs, why don't you just either intercept keyevents and test for their validity (by creating the string in memory) or just delete the last character in the field?

like image 7
Georg Schölly Avatar answered Nov 10 '22 00:11

Georg Schölly


Do you really want to do this with a regex?

function valid(f) {
    if(isNaN(f)){return false;}
    return 100 * f == parseInt(100*f,10);
}
like image 3
Ken Avatar answered Nov 10 '22 00:11

Ken


gs: This is very close, but the line

f.value = f.value.replace(/[^\d\.]/g, "");

Doesn't actually appear to work. In fact I lose focus of the text box for some reason. Although perhaps it's my code ;)

like image 2
Kezzer Avatar answered Nov 09 '22 23:11

Kezzer