views:

197

answers:

2

Hello All,

Please help with me writing a JavaScript Validation for currency/money field.

So please provide any regular expressions if u have :)

Also, for my region, don't need any currency symbols like '$' in the field.

Only decimals are to be included for validation as special chars., along with numbers.

A: 
/[1-9]\d*(?:\.\d{0,2})?/

[1-9] - must start with 1 to 9
\d* - any number of other digits
(?: )? - non capturing optional group
\. - a decimal point
\d{0,2} - 0 to 2 digits

does that work for you? or maybe parseFloat:

var float = parseFloat( input );
meouw
I don't think `parseFloat` or `parseInt` are that great for validation, they will parse strings like "123abc" as "123". Also, your regex tests true on the following string: `"a01.9bc"`, you need to add `^` and `$` to match the beginning and end of the string respectively. Actually, even then a string like "0.91" won't work.
Andy E
Yes, you're right, Andy E has provided a better answer
meouw
Thanx a lot...!
dev646
+1  A: 

You could use a regexp:

var regex  = /^\d+(?:\.\d{0,2})$/;
var numStr = "123.20";
if (regex.test(numStr))
    alert("Number is valid");

If you're not looking to be as strict with the decimal places you might find it easier to use the unary (+) operator to cast to a number to check it's validity:

var numStr = "123.20";
var numNum = +numStr; // gives 123.20

If the number string is invalid, it will return NaN (Not a Number), something you can test for easily:

var numStr = "ab123c";
var numNum = +numStr;
if (isNaN(numNum))
    alert("numNum is not a number");

It will, of course, allow a user to add more decimal places but you can chop any extra off using number.toFixed(2) to round to 2 decimal places. parseFloat is much less strict with input and will pluck the first number it can find out of a string, as long as that string starts with a number, eg. parseFloat("123abc") would yield 123.

Andy E
wow ... feeling better now... that was good... Thanx!
dev646