jQuery Form Validation before Ajax submit

We have already explained about form validation using same technologies. Now, the same can be done by using Ajax, In this blog post we will tell you how it can be done.

We have created an HTML form with four input fields and validation of each field is done by using combine logic of Ajax, PHP and JQuery.

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="ajax.php" 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="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/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) {
			$.ajax({
				url: form.action,
				type: form.method,
				data: $(form).serialize(),
				dataType: "json",
				success: function(response) {
					alert(response.message);
					location.reload();
				}            
			});
		}
	});
	
	jQuery.validator.addMethod("lettersonly", function(value, element) {
	  return this.optional(element) || /^[a-z]+$/i.test(value);
	}, "Letters only please"); 

});
</script>
</body>
</html>

ajax.php file

<?php
$firstname = $_POST['firstname'];
$lastname =  $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$json['message'] = "Data Suucessfully Display!!";
echo json_encode($json);
?>

Leave a Reply

Your email address will not be published. Required fields are marked *