views:

2126

answers:

4

My Regular Expressions knowledge is next to none but I'm having to have some client-side valiation against a text box which only allows numbers up to two decimal points 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.

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

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

AnthonyWJones
Ah very nice, however, I need to match an empty string. If an empty string is provided and the form is submitted, the value defaults back to zero.
Kezzer
Additionally, if you enter "123." then I'd receive an error as soon as I placed the dot in the input box, so whilst useful, it's only actually good for the form submition. This stage is the actual input stage.
Kezzer
+3  A: 

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

Georg
Deleting the last character in the field to check for validity would be useful, only if it's a "." character though.
Kezzer
A: 

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

Kezzer
alert("Test10.50Test".replace(/[^\d\.]/g, "")); gives 10.50 back, therefore it should work. What isn't working is for example when there are more than one dot.
Georg
It's for live input though, so that would work usually, but when actually doing it against live input it doesn't appear to work for me. I could have something wrong, however.
Kezzer
+1  A: 

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);
}
Ken