dsp77 Posted April 12, 2011 Share Posted April 12, 2011 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 More sharing options...
Adam Posted April 12, 2011 Share Posted April 12, 2011 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 https://forums.phpfreaks.com/topic/233473-javascript-validate-numeric-and-decimal/#findComment-1200567 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.