Jump to content

javascript validate numeric and decimal


dsp77

Recommended Posts

hello there, i have the following code to validate if empty input but i want to validate and the input for numeric or decimal, valid entries: 0.23, 1.22, 3, 0, 7 etc.  thank you

<script type = "text/javascript">
function validateForm(form) {
for(var i = 0; i < form.elements.length; i++){
	if(form.elements[i].value.length == 0){
		document.getElementById(form.elements[i].name).setAttribute("class", "error");
		alert('You have an empty field: '+form.elements[i].name+'.');
		form.elements[i].focus();
		return false;
	}
} return true;
}
</script>

Link to comment
https://forums.phpfreaks.com/topic/233473-javascript-validate-numeric-and-decimal/
Share on other sites

There's a few ways. If you want strict validation, cast the value as a number by subtracting it by 0 (therefore the numeric value won't have changed) and compare it to its string value. For example with your code:

 

if ((form.elements[i].value - 0) != form.elements[i].value) {
    // invalid
}

 

Might want to store that value in a variable to make it a little more readable.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.