JavaScript Validation is important, because before sending the web page to the server, we have to make sure that input are acceptable. In any web page, we may accept Mobile Number , Email, Age, Date of Birth as input. Before sending these input to server, we have to validate the input whether having proper values / format or not. For example Mobile Number field should have only Numeric (Digits 0-9) .
In this example, let us check whether given mobile number is valid or not. That means we have to ensure, the mobile number field should have only digits (0-9) and it has length of 10.
The following isNumeric(String) function checks the given mobile number is having only numeric values. If the field has other than 0-9, then it will return false.
<script language="javascript" > function isNumeric(str) { var allowedChars = "0123456789"; // For Checking Decimal , allowedChars = "0123456789."; var isDigit=true; var char; for (i = 0; i < str.length && isDigit == true; i++) { char = str.charAt(i); if (allowedChars.indexOf(char) == -1) isDigit = false; } return isDigit; } function submitForm() { var phone=window.document.productForm.qty.value; if (isNumeric(phone)==false || phone.length!=10) { alert ("Please enter 10 digit number 0-9"); return; } } </script> ... ..... <form name="empForm" ... method="post" action="/employee.do"> .... .... <TR> <TD width="202">Phone </TD> <TD width="270"> <input type="text" name="phone"> </html:text> </TD> </TR> <TR> <TD > <input type="button" value="Submit" onClick="submitForm()"> </TD> </TR> ....... ...... </form>