JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be:
– has the user left required fields empty?
– has the user entered a valid e-mail address?
– has the user entered a valid date?
– has the user entered text in a numeric field?
First of all, all the required fields are checked in the form. For example, the function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:
1 2 3 4 5 6 7 8 9 |
function validateForm() { var x=document.forms["myForm"]["fname"].value if (x==null || x=="") { alert("First name must be filled out"); return false; } } |
An alternate way is to call the function when the form is being submitted:
1 2 3 4 |
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post"> First name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> |
JavaScript is also used to check whether the content of an email is valid or not. This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must not be the first character of the email address, and the last dot must be present after the @ sign, and minimum 2 characters before the end. The function to perform these tasks is as follows:
1 2 3 4 5 6 7 8 9 10 11 |
function validateForm() { var x=document.forms["myForm"]["email"].value var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } } |
Like simple forms, this function can also be called when the email is being sent:
1 2 3 4 |
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post"> Email: <input type="text" name="email"> <input type="submit" value="Submit"> </form> |
With JavaScript validation, user can save time since if not validated; they would have to change the data later when they come to know about its absence.