Javascript Form Validation
The javascript provides you the facility the validate the form on the client side so processing will be fast than server-side validation. So, most of the web developers prefer javascript validation.It is important to validate the form submitted by the user because it can have inappropriate values. So validation is must.
Through javascript, we can validate name, password, email, date, mobile number etc fields.
Example of javascript form validation
In this example, we are going to validate the name and password. The name can’t be empty and password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the next page until given values are correct.
- <script>
- function validateform(){
- var name=document.myform.name.value;
- var password=document.myform.password.value;
- if (name==null || name==""){
- alert("Name can't be blank");
- return false;
- }else if(password.length<6){
- alert("Password must be at least 6 characters long.");
- return false;
- }
- }
- </script>
- <body>
- <form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
- Name: <input type="text" name="name"><br/>
- Password: <input type="password" name="password"><br/>
- <input type="submit" value="register">
- </form>
Output of the above example
Javascript email validation
We can validate the email by the help of javascript.
There are many criteria that need to be follow to validate the email id such as:
- email id must contain the @ and . character
- There must be at least one character before and after the @.
- There must be at least two characters after . (dot).
Let's see the simple example to validate the email field.
- <script>
- function validateemail()
- {
- var x=document.myform.email.value;
- var atposition=x.indexOf("@");
- var dotposition=x.lastIndexOf(".");
- if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
- alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"
- +dotposition);
- return false;
- }
- }
- </script>
- <body>
- <form name="myform" method="post" action="abc.jsp" onsubmit="return validateemail();">
- Email: <input type="text" name="email"><br/>
- <input type="submit" value="register">
- </form>
No comments:
Post a Comment