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
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.