JavaScript Form Validation
JavaScript Form Validation
It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most of the web developers prefer
JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers
and more fields.
Here, we are validating the form on form submit. The user will not be forwarded to
the next page until given values are correct.
1. <script>
2. function validateform(){
3. var name=document.myform.name.value;
4. var password=document.myform.password.value;
5.
6. if (name==null || name==""){
7. alert("Name can't be blank");
8. return false;
9. }else if(password.length<6){
10. alert("Password must be at least 6 characters long.");
11. return false;
12. }
13. }
14. </script>
15. <body>
16. <form name="myform" method="post" action="abc.jsp" onsubmit="return validatef
orm()" >
17. Name: <input type="text" name="name"><br/>
18. Password: <input type="password" name="password"><br/>
19. <input type="submit" value="register">
20. </form>
1. <script>
2. function validate(){
3. var name=document.f1.name.value;
4. var password=document.f1.password.value;
5. var status=false;
6.
7. if(name.length<1){
8. document.getElementById("nameloc").innerHTML=
9. " <img src='unchecked.gif'/> Please enter your name";
10. status=false;
11. }else{
12. document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";
13. status=true;
14. }
15. if(password.length<6){
16. document.getElementById("passwordloc").innerHTML=
17. " <img src='unchecked.gif'/> Password must be at least 6 char long";
18. status=false;
19. }else{
20. document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";
21. }
22. return status;
23. }
24. </script>
25.
26. <form name="f1" action="#" onsubmit="return validate()">
27. <table>
28. <tr><td>Enter Name:</td><td><input type="text" name="name"/>
29. <span id="nameloc"></span></td></tr>
30. <tr><td>Enter Password:</td><td><input type="password" name="password"/>
Output:
Enter Name:
Enter Password:
register
There are many criteria that need to be follow to validate the email id such as:
1. <script>
2. function validateemail()
3. {
4. var x=document.myform.email.value;
5. var atposition=x.indexOf("@");
6. var dotposition=x.lastIndexOf(".");
7. if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
8. alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:
"+dotposition);
9. return false;
10. }
11. }
12. </script>
13. <body>
14. <form name="myform" method="post" action="#" onsubmit="return validateemail
();">
15. Email: <input type="text" name="email"><br/>
16.
17. <input type="submit" value="register">
18. </form>