1reference : https://www.sitepoint.com/basic-jquery-form-validation-tutorial/
2
3// Wait for the DOM to be ready
4$(function() {
5 // Initialize form validation on the registration form.
6 // It has the name attribute "registration"
7 $("form[name='registration']").validate({
8 // Specify validation rules
9 rules: {
10 // The key name on the left side is the name attribute
11 // of an input field. Validation rules are defined
12 // on the right side
13 firstname: "required",
14 lastname: "required",
15 email: {
16 required: true,
17 // Specify that email should be validated
18 // by the built-in "email" rule
19 email: true
20 },
21 password: {
22 required: true,
23 minlength: 5
24 }
25 },
26 // Specify validation error messages
27 messages: {
28 firstname: "Please enter your firstname",
29 lastname: "Please enter your lastname",
30 password: {
31 required: "Please provide a password",
32 minlength: "Your password must be at least 5 characters long"
33 },
34 email: "Please enter a valid email address"
35 },
36 // Make sure the form is submitted to the destination defined
37 // in the "action" attribute of the form when valid
38 submitHandler: function(form) {
39 form.submit();
40 }
41 });
42});
1<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
2then add javascript code:
3$(document).ready(function() {
4 $("#form").validate();
5});
6</script>
1jQuery(document).ready(function() {
2 jQuery("#forms).validate({
3 rules: {
4 firstname: 'required',
5 lastname: 'required',
6 u_email: {
7 required: true,
8 email: true,//add an email rule that will ensure the value entered is valid email id.
9 maxlength: 255,
10 },
11 }
12 });
13});
1$('form[id="second_form"]').validate({
2 rules: {
3 fname: 'required',
4 lname: 'required',
5 user_email: {
6 required: true,
7 email: true,
8 },
9 psword: {
10 required: true,
11 minlength: 8,
12 }
13 },
14 messages: {
15 fname: 'This field is required',
16 lname: 'This field is required',
17 user_email: 'Enter a valid email',
18 psword: {
19 minlength: 'Password must be at least 8 characters long'
20 }
21 },
22 submitHandler: function(form) {
23 form.submit();
24 }
25});
26
1function submitFunction(event){
2 event.preventDefault();
3}
4$("#form_id").submit(submitFunction);
1<html>
2<body>
3<h2>Validation of a form</h2>
4<form id="form" method="post" action="">
5First name:<br>
6<input type="text" name="firstname" value="john">
7<br>
8Last name:<br>
9<input type="text" name="lastname" value="Doe">
10<br>
11Email:<br>
12<input type="email" name="u_email" value="johndoe@gmail.com">
13<br>
14<br><br>
15<input type="submit" value="Submit">
16</form>
17</body>
18</html>