Here I will explain a little bit about validating forms using Javascript. It also has its own limitations such as it cannot be use on browsers that have javascript disabled. But yet it is very useful in validating content entered by a visitor. For this script we have to follow two main steps.
- Assign a name to the form and the following onsubmit event. (<form action="" method="" name"form" onsubmit="return validate_form();">...</form> )
- Edit and add the following code before the </body> tag.
<script language="javascript"> function echeck(str) { var at="@" var dot="." var lat=str.indexOf(at) var lstr=str.length var ldot=str.indexOf(dot) if (str.indexOf(at)==-1){ alert("Invalid E-mail ID") return false } if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ alert("Invalid E-mail ID") return false } if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ alert("Invalid E-mail ID") return false } if (str.indexOf(at,(lat+1))!=-1){ alert("Invalid E-mail ID") return false } if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ alert("Invalid E-mail ID") return false } if (str.indexOf(dot,(lat+2))==-1){ alert("Invalid E-mail ID") return false } if (str.indexOf(" ")!=-1){ alert("Invalid E-mail ID") return false } return true } function validate_form() { var emailID=document.form.email if ((emailID.value==null)||(emailID.value=="")){ alert("Please Enter your Email ID") emailID.focus() return false } if (echeck(emailID.value)==false){ emailID.value="" emailID.focus() return false } //All the code above this will check if the email id contains some characters //then @ symbol then . and again some characters. if(document.form.name.value=="") //This will validate the form with name form and field with name field1. { alert("Please enter your name!"); //This will give the alert message if the field is blank. document.form.name.focus(); //This will bring the error field to focus. return false; //This will prevent the form from submitting } if(document.form.subject.value=="") { alert("Please enter a subject!"); document.form.subject.focus(); return false; } if(document.form.message.value=="") { alert("Please enter your message!"); document.form.message.focus(); return false; } return true } </script>
You must create a form and add name tag to that form. Also you must add a name tag to each of the input fields and customize the above script according to that.
I won't explain this in more details as I believe if you are looking for form validation it means that you know what I meant about customizing the above script.
If you still have problems, you can leave a comment here and I will be happy to help you.
No comments:
Post a Comment
Comment anything you want. Just be polite and give respect to others!
I am simply going to remove the comments which are offensive or are off topic.
And please don't spam your website links in comments. I don't, neither should you.