For working professionals
For fresh graduates
More
2. jQuery Ajax
3. jQuery CSS
12. Jquery Toggle
14. jQuery html()
20. jQuery Animation
Validating the data given in forms is usually a good idea when you include forms on your website for user input. jQuery validation guarantees that the data that your application can process is received in an appropriate format and improves the user experience (UX) by allowing users to get error messages and suggestions for appropriate data types.
jQuery validation comes in two different types: server-side and client-side. You should do both; it is advised. Before a request to the server is made with the data, client-side validation—which is typically accomplished with JavaScript—serves to provide the user with prompt feedback on input problems. An additional layer of protection against erroneous data is provided by server-side validation. JavaScript can be circumvented, so even if you have client-side validation configured you should always run server-side validation.
This article will examine the use of jQuery for client-side validation. There are two methods we will look at. In the second example, we will demonstrate how to use the jQuery Validation Plugin to streamline the process of validating data on a form. Initially, we will create the validation rules from scratch.
In the following guide, you will learn how to utilize the jQuery form validation plugin to quickly validate your forms.
Let’s start by putting jQuery within your HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Next, add the following form to the file:
<h2>Example 1:</h2>
<form id="first_form" method="post" action="">
<div>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name"></input>
</div>
<div>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name"></input>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email"></input>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password"></input>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
A basic form with four fields and a submit button is shown in the markup above.
Include the CSS styles shown below:
form label {
display: inline-block;
width: 100px;
}
form div {
margin-bottom: 10px;
}
.error {
color: red;
margin-left: 5px;
}
label.error {
display: inline;
}
The output:
Next, please add the JavaScript code that I have provided below:
$(document).ready(function() {
$('#first_form').submit(function(e) {
e.preventDefault();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
var password = $('#password').val();
$(".error").remove();
if (first_name.length < 1) {
$('#first_name').after('<span class="error">This field is required</span>');
}
if (last_name.length < 1) {
$('#last_name').after('<span class="error">This field is required</span>');
}
if (email.length < 1) {
$('#email').after('<span class="error">This field is required</span>');
} else {
var regEx = /^[A-Z0-9][A-Z0-9._%+-]{0,63}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/;
var validEmail = regEx.test(email);
if (!validEmail) {
$('#email').after('<span class="error">Enter a valid email</span>');
}
}
if (password.length < 8) {
$('#password').after('<span class="error">Password must be at least 8 characters long</span>');
}
});
});
The code above creates a listener on the form, which will be called upon submission. To stop the form's data from being submitted, we first execute preventDefault() in the listener. Next, we make a few variables and give them the values of the various form fields.
Put the $(".error"). away. For the time being, we'll ignore the remove(); statement.
We perform several tests on the form's field values to determine their validity after we have them. We verify if input is present in the first_name, last_name, and email fields. A span tag containing an error message will be added after a field if the user leaves it blank.
To further ensure that the data supplied in the email box is a proper format for an email address, we add another check. For this check, a regular expression is employed.
Lastly, we make sure the password has a minimum of eight characters by checking its length.
Immediately preceding the code that verifies the fields is the line $(".error").remove();. Any element in the documents that has the error class removed as a result. This guarantees that the form won't have the prior error messages when it is submitted again. If we omitted this, an error message would be added to the previous error message each time the form was submitted with an error, causing the form to display several error messages.
Try filling out the form with inaccurate information, and you will get the error warnings, as I have shown below:
I created code in the preceding example to validate the form data on a first-hand basis. You can use a library such as the jQuery Validation Plugin to speed up and simplify this procedure. With this, the plugin will handle validation for you; all you need to do is set a few criteria for each field on your form that needs to be validated.
Include the library in your file before you can see this in effect. The plugin depends on the jQuery script tag, so do not remove it.
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
Next, add a form to the file:
<h2>Example 2:</h2>
<form id="second_form" method="post" action="">
<div>
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname"></input>
</div>
<div>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname"></input>
</div>
<div>
<label for="user_email">Email:</label>
<input type="email" id="user_email" name="user_email"></input>
</div>
<div>
<label for="psword">Password:</label>
<input type="password" id="psword" name="psword"></input>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
Next, please include the following Javascript code in the $(document).ready(function() {}) block, after the $('#first_form').submit(function(e) {}) block.
$('form[id="second_form"]').validate({
rules: {
fname: 'required',
lname: 'required',
user_email: {
required: true,
email: true,
},
psword: {
required: true,
minlength: 8,
}
},
messages: {
fname: 'This field is required',
lname: 'This field is required',
user_email: 'Enter a valid email',
psword: {
minlength: 'Password must be at least eight characters long'
}
},
submitHandler: function(form) {
form.submit();
}
});
We update every field on the form with the necessary rule. We include an email rule in the email field to make sure the value submitted is a legitimate email address. An additional rule in the password field makes sure the password is at least eight characters long.
We set the error messages that will appear if a rule fails after defining the rules.
You should still be able to receive validation for the form fields when you launch the page and test the form.
Form validation is a critical aspect of web development, ensuring data integrity and improving the user experience. While basic validation techniques are essential, advanced validation strategies can significantly enhance the functionality and usability of web forms. The following section explores advanced validation techniques such as remote validation, error placement strategies, and handling complex validation scenarios.
Remote validation involves checking form data against server-side databases without requiring a page reload. This technique is particularly useful for verifying unique data, such as usernames or email addresses, where the data must be checked against existing records in a database.
Below are the steps involved in how remote validation works:
Proper error message placement is vital for the user experience. Incorrect or poorly placed error messages can confuse users and lead to frustration.
Best practices for error placement are given below:
Example Implementation:
<form id="example-form">
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email">
<span id="email-error" class="error-message"></span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password">
<span id="password-error" class="error-message"></span>
</div>
<button type="submit">Submit</button>
</form>
Javascript:
$('#example-form').on('submit', function(event) {
event.preventDefault();
var isValid = true;
if (!validateEmail($('#email').val())) {
$('#email-error').text('Invalid email address');
isValid = false;
} else {
$('#email-error').text('');
}
if (!validatePassword($('#password').val())) {
$('#password-error').text('Password must be at least 8 characters');
isValid = false;
} else {
$('#password-error').text('');
}
if (isValid) {
// Submit the form via Ajax or other methods
}
});
Complex validation scenarios involve conditions where the validation requirements depend on user input or other dynamic factors.
Conditional validation is necessary when the validation rules for one field depend on the value of another field. For example, an additional address field might be required if a user selects a specific country.
Example Implementation:
<form id="conditional-form">
<div class="form-group">
<label for="country">Country</label>
<select id="country" name="country">
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="Other">Other</option>
</select>
</div>
<div class="form-group" id="state-group" style="display: none;">
<label for="state">State</label>
<input type="text" id="state" name="state">
<span id="state-error" class="error-message"></span>
</div>
<button type="submit">Submit</button>
</form>
Javascript:
$('#country').on('change', function() {
if ($(this).val() === 'USA') {
$('#state-group').show();
} else {
$('#state-group').hide();
$('#state-error').text('');
}
});
$('#conditional-form').on('submit', function(event) {
event.preventDefault();
var isValid = true;
if ($('#country').val() === 'USA' && !$('#state').val()) {
$('#state-error').text('State is required for USA');
isValid = false;
} else {
$('#state-error').text('');
}
if (isValid) {
// Submit the form via Ajax or other methods
}
});
jQuery form submit validation simplifies the process of validating user input by providing a comprehensive set of functions and methods to handle various validation scenarios. Whether you are validating simple text inputs or complex multi-step forms, jQuery has you covered.
And with that, you are done! You now understand how to configure jQuery form validation with a customized error message. Remember that this is not a substitute for server-side validation. Malicious users may still be able to alter or get around the validation rules (for instance, by utilizing the developer tools in the browser).
1. Why use the jQuery validation?
jQuery validation enhances user experience by providing real-time feedback on form inputs, reducing errors, and improving data integrity.
2. How do I include jQuery validation in my project?
You can include jQuery validation by downloading the library from the official website or linking to it via a CDN in your HTML file.
3. What types of validation can jQuery validation handle?
jQuery validation can handle various types of validation, including required fields, email format, numeric inputs, and custom validation rules.
4. Can jQuery validation be customized?
Yes, jQuery validation offers extensive customization options, allowing you to define custom error messages, validation rules, and styles to fit your project's needs.
5. Does jQuery validation work with all form elements?
jQuery validation is compatible with most HTML form elements, including text inputs, checkboxes, radio buttons, select dropdowns, and areas.
6. Is jQuery validation secure?
jQuery validation helps improve security by preventing invalid data submissions, but additional server-side validation is necessary to ensure full data integrity and security.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.