How to validation form in jquery
This tutorial shows you how to set up a basic form validation with jQuery, demonstrated by a simple registration form.
We’re going to use the jQuery Validation Plugin to validate our form. The basic principle of this plugin is to specify validation rules and error messages for HTML elements in JavaScript.
Example
<html>
<head>
<title>Form Validation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form action="" method="post" id="register-form" >
First Name
<input type="text" id="firstname" name="firstname" />
Last Name
<input type="text" id="lastname" name="lastname" />
Email
<input type="text" id="email" name="email" />
Password
<input type="password" id="password" name="password" />
<input type="submit" name="submit" value="Submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.min.js"></script>
<script>
$(function() {
$("#register-form").validate({
rules: {
firstname: "required",
lastname: {
required: true,
lettersonly: true
},
email: {
required: true,
email: true
},
password: {
required: true,
number: true,
minlength: 5
}
},
messages: {
firstname: "Please enter your first name",
lastname: {
required: "Please enter your last name",
lettersonly: "Please enter only alphabetical characters"
},
password: {
required: "Please provide a password",
number: "Please provide a Numeric value",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address",
},
submitHandler: function(form) {
form.submit();
}
});
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
});
</script>
</body>
</html>
Leave a Reply