In this post , we will learn about jquery validations. Here we have 2 parts, first is HTML code and the second is JavaScript code.
Using a jQuery plugin to validate forms serves a lot of purposes. It gives you additional abilities like easily displaying custom error messages and adding conditional logic to form validation. A validation library can also help you add validation to your HTML forms with minimal or no changes to the markup. The conditions for validity can also be added, removed, or modified at any time with ease.
HTML part
You can start using this plugin without making any significant changes to your markup. The only thing that you might have to change is to add an id or class to the form you want to validate if it doesn’t have one already.
<html>
<head>
<title>Jquery form validation example</title>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style>
#form label.error {
color: red;
font-weight: bold;
}
.main {
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="main">
<h1>Registration</h1>
<form action="actionpage.php" id="form">
<div class="form-group">
<label for="login">Login</label>
<input type="text" name="login" class="form-control">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Register" class="submit" class="form-control">
</div>
</form>
</div>
</body>
</html >
Jquery Part
<script type="text/javascript">
$().ready(function() {
$("#form").validate({
rules : {
login : {
required : true
},
email : {
required : true,
email : true
},
password : {
required : true,
minlength : 5,
maxlength : 8
}
},
messages: {
login: "Enter you login",
password: {
required: "Enter your password",
minlength: "Minimum password length is 5",
maxlength: "Maximum password length is 8"
},
email: "Enter your email"
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>