Monday, August 31, 2009

How to check two decimal validation in java script?

function MoneyValidation()
{
var value1 = document.formaName.fieldName.value;
if(value1.indexOf(".") != -1)
{
if(!/\.[0-9]{1,2}$/.test(value1))
{
alert("value1 should be two fractional positions required");
return false;
}
}

return true;
}

The above function validates up to two decimal positions.
This function allows a value1 with out decimal position.
If there is a decimal point then the field should have at least one number after decimal point the maximum number of digits after the decimal point is two. It wont accept more then two digits after the decimal point.

The indexOf(".") function will return -1 if there is no decimal point the else block will execute that mean true will be return.
If there is a decimal point in value1 then indexOf(".") returns the value >0 according to the didits present before the decimal point. So that it do the validation.

The regular expression validates the number of digits after the decimal point.

No comments:

Post a Comment

Please comment on this