macklin
macklin

Reputation: 375

Regexp for validating decimals not working

I have a form that has a field that takes what a decimal value. The desired requirements for this decimal are that it be in the form ##.## with two numbers on each side of the decimal point.

I found a regex online that is supposed to validate the decimal, but instead views any input as invalid. Here is the code I have:

function validateDecimal(number)
{
eval("var stringvar=/^[-+]?([0-9]*\\.[0-9]{0,2})|([0-9]+)$/");

return stringvar.test(number);
}

And the call...

var numStr = document.getElementById('Amount');
if (!validateDecimal(numStr)) {
    alert("Please enter a valid dollar amount in the form ##.##");
    return false;
}

I understand that this regex is not exactly what I'm looking for, but I can't seem to figure out why it views all input as invalid. Does anyone know what I'm doing wrong?

Upvotes: 1

Views: 79

Answers (2)

johnr
johnr

Reputation: 347

first off, you shouldn't be using eval like that, it puts unnecessary stress on the client, just do

var regex = /^[-+]?([0-9]*\\.[0-9]{0,2})|([0-9]+)$/;
return regex.test(number);

instead.

And you need to use .value after getElementById('Amount');

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

The first problem is that you forgot to grab the actual value of your input:

document.getElementById('Amount').value

The second problem is eval, you don't need it here, you can write it like this:

var stringvar = /^[-+]?([0-9]*\.[0-9]{0,2})|([0-9]+)$/;

And third, here's the regex I propose if your number must always be XX.XX:

/^[+-]?\d\d\.\d\d$/

Upvotes: 6

Related Questions