Client-side validation

Form validation is a crucial aspect of web development, ensuring that user-provided data is correct and useful before it's processed. jQuery, a fast and concise JavaScript library, simplifies the process of client-side validation. This lesson will delve into using jQuery to validate form data, providing immediate feedback to users and preventing the submission of invalid forms.

Desired Outcomes

  • Understand the Basics of jQuery Validation: Learn the principles behind client-side validation using jQuery.
  • Implementing jQuery Validation: Gain the ability to apply jQuery validation methods to HTML forms.
  • Customizing Validation Rules: Learn to create custom validation rules tailored to specific form requirements.
  • Displaying Error Messages: Understand how to effectively communicate validation errors to users.
  • Integrating with a User Interface: Apply validation in a way that is seamlessly integrated with the overall user interface.

Using JQuery, client-side validation is pretty straightforward to implement. While there are more cases that developers can test, it is most often checked whether a certain field is filled, the validity of emails, phone numbers, and similar.

It is necessary to emphasize that it is desirable to perform validation on the server side as well. Despite this, for a better user experience, it is also desirable to check the input data before the form is sent.

With that being said, let's jump on in to some examples! First, we'll see how easy it is to check if a required field doesn't have anything in it. If it doesn't, then we'll return false, and prevent the form from processing.

$( "#form" ).submit(function( event ) {
  // Check if the length of the content inside the element is zero
  if ( $( ".input" ).val().length === 0 ) {
      // Output message
      alert("The field is required!");
      // Disable form submission if the field is not filled
      event.preventDefault();
  } else {
      // $.ajax function
  }
});

In the following example, it checks whether there is a number inside the text field:

$( "#form" ).submit(function( event ) {
  var phone = $( "#phone" ).val();
  // Checking numbers
  var phoneRegex = /^\d*$/;
  // check if the entered data is a number
  if ( !phoneRegex.test(phone) ) {
  // Disable form submission if the field is not filled with a number
      event.preventDefault();
  } else {
      // $.ajax function
  }
});

 

In summary, this jQuery script ensures that the form is not submitted unless the phone number field contains only digits. If the entered phone number is not valid, the form submission is prevented, thereby enforcing a basic data validation on the client side. This is a common practice in web forms to ensure the integrity of the data being sent to the server.

Setting Up jQuery Validation

First, ensure that you have included jQuery and the jQuery Validation Plugin in your HTML file:

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.19.2/jquery.validate.min.js">
</script>

Basic Form Validation

Create an HTML form that you want to validate:

<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required />
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required />
  <input type="submit" value="Submit" />
</form>

Add jQuery validation to your form:

$(document).ready(function () {
  $("#myForm").validate();
});

 

Here, the validate method is called on the form with id="myForm". jQuery Validation Plugin automatically validates the form upon submission. Fields with the required attribute must be filled, and the email field must contain a valid email address.

Custom Validation Rules

You can define custom validation rules for more specific requirements:

$("#myForm").validate({
  rules: {
    name: {
      required: true,
      minlength: 2,
    },
    email: {
      required: true,
      email: true,
    },
  },
  messages: {
    name: {
      required: "Please enter your name",
      minlength: "Your name must consist of at least 2 characters",
    },
    email: "Please enter a valid email address",
  },
});

Custom rules are set for the name and email fields. For example, the name field must be at least 2 characters long. Custom messages are also provided to replace default error messages.

Displaying Error Messages

By default, error messages are displayed right next to the input fields. You can customize this behavior:

$("#myForm").validate({
  // Existing rules...
  errorElement: "div",
  errorPlacement: function (error, element) {
    error.appendTo(element.parent("div"));
  },
});

This configuration changes the error message element to div and places it within the parent div of the input field.

Advanced Techniques and Custom Validators

You can also write custom validator methods for complex scenarios.

$.validator.addMethod(
  "noSpace",
  function (value, element) {
    return value.indexOf(" ") < 0 && value != "";
  },
  "No space allowed"
);


$("#myForm").validate({
  rules: {
    name: {
      noSpace: true,
    },
    // Other rules...
  },
  // Existing configuration...
});

A custom method noSpace is defined to disallow spaces in the input. It's then used as a rule for the name field.

By mastering jQuery validation, you enhance the user experience by providing immediate, intuitive feedback on form inputs, ensuring that only valid data is submitted. This lesson should equip you with the knowledge to implement effective client-side validation using jQuery, significantly improving the functionality and user-friendliness of your web forms.

Updated on:

Part of our complete: JQuery guide

Want exercises and real projects for this lesson? Get the full course.