Currency validation

Viewed 83285

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.

6 Answers

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.

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

 let amount = document.querySelector('#amount'), preAmount = amount.value;
        amount.addEventListener('input', function(){
            if(isNaN(Number(amount.value))){
                amount.value = preAmount;
                return;
            }

            let numberAfterDecimal = amount.value.split(".")[1];
            if(numberAfterDecimal && numberAfterDecimal.length > 3){
                amount.value = Number(amount.value).toFixed(3);;
            }
            preAmount = amount.value;
        })
<input type="text" id="amount">

Now I use this:

let func = function (vStr) {
    let v0 = Number(vStr);
    let v1 = Number(v0.toFixed(2));
    return v0 === v1;
};

Note that, NaN === NaN returns false. Maybe some substitution for '$' and ',' before parsing is needed, for other cases. And there is a problem of precision for very large number, longer than 16 digits. As well as values of '0x3a', '68n' is considered valid.

Nowadays, <input> of type="number", with step='.01' may be more proper.

Related