In this example we are going to study the validation of a Form using Jquery.
To start with, you need to include the below plugin in your jsp file where you are going to create a form.
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js
Now let's create a simple form with 2 input fields email and password as shown below.
<form id="Loginform" method="post" action="Form">
<div>
<label>Email:</label>
<input type="text" id="email" name="email"/>
</div>
<div>
<label>Password:</label>
<input type="password" id="pass" name="pass"/>
</div>
<div>
<input type="submit" value="Submit"/>
</div>
</form>
The method attribute in the <form> tag specifies the HTTP method(POST or GET) to send the data.
The action attribute in the <form> tag specifies where to send the data. Here I am sending the data to Form.java .
Below is the css style which I have added to design the form:
<style>
form label{
width:100px;
display:inline-block;
}
form div{
margin-bottom:10px;
}
label.error{
display: inline;
margin-left: 5px;
color: red;
}
</style>
In the above css style, form label indicates that all the label tags inside the form takes the style which is specified.
Similarly, form div indicates that all the div inside the form takes the style which is specified.
label.error indicates that the style will be applicable to all the labels with class="error".
Below code explains the jquery validation for a form:
<script>
$.validator.addMethod("email", function (value, element) {
return /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value);
});
jQuery(document).ready(function ($) {
$("#Loginform").validate({
rules: {
email: {
required: true,
email: true,
},
pass: {
required: true,
minlength: 6,
}
},
messages: {
email: {
required: "This field is required",
email: "Please enter a valid email",
},
pass: {
required: "This field is required",
minlength: "Please enter minimum 6 characters",
}
}
});
});
</script>
Loginform is the form id to be validated.
rules indicates validation rules to be specified.
email and pass are the name attribute of the input fields which has to be validated.
required - Specifies that the field is required and should not be empty.
email - Specifies that the entered email should be valid. To validate I have created email method by using addMethod which checks the entered value with the regular expression and returns true if matches.
minlength - Specifies the minimum password length.
messages indicates the validation error messages .
Now, try to submit the form with invalid data and check the error messages.
