Bladephp: Now with 8+ codeigniter, php, and laravel project 8+ php project From $37/Month From Rs. 2499/Month

How to form validation in jquery

by
Category:javascript
javascript jquery
How to form validation 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" /><br /><br />
	Last Name
	<input type="text" id="lastname" name="lastname" /><br /><br />
	Email
	<input type="text" id="email" name="email" /><br /><br />
	Password
	<input type="password" id="password" name="password" /><br /><br />
	<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="http://bladephp.co/download/js/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>

0 Comments


Html code work in comment box


Related Post