How to validate only digits and decimal points in Javascript?

Our company had implemented an online payment form where customers could pay online on the company website against outstanding invoices or any other service. However, the validation on the form regarding the payment amount field was pretty simple as it was just checking whether the customer had input amount in the field or not and not whether the format of the data was correct or not. For e.g. the customer could have just entered some alphabets and the validation would not have been able to pick it.

Even though this problem would not have caused any major problem and the payment mechanism later on would have caught it, the issue still had to be resolved as it was bad in terms of user friendliness. I coded a function which would check for illegal values and point them out to the user.

function numFilter(input) {
s = input.value;
filteredValues = "1234567890.";
var numValid = 0;
for (i = 0; i < s.length; i++) {  
	var c = s.charAt(i);
	if (filteredValues.indexOf(c) == -1) {} else { numValid++ };
}
if (numValid == s.length) 
        return true;
else
	return false;	
}

The above function checks whether the input values in the text box are numbers and decimal point and alerts if a character other than the above is used. The function could also be used on the onkeypress event of the input box with slight modifications.

Hope the above helped.

Leave a Reply

Your email address will not be published. Required fields are marked *