</>
Skip to content
jQuery lessons (35/39)

jQuery — Validation

Basic Validation

$("form").submit(function(e) {
    var name = $("#name").val();
    if (name === "") {
        alert("Name is required");
        e.preventDefault();
    }
});

jQuery Validate Plugin

$("form").validate({
    rules: {
        name: { required: true, minlength: 2 },
        email: { required: true, email: true },
        age: { required: true, number: true, min: 18 }
    },
    messages: {
        name: "Please enter your name",
        email: "Please enter a valid email",
        age: "You must be at least 18"
    }
});

Validation Rules

RuleDescription
requiredField must not be empty
emailMust be valid email format
urlMust be valid URL
numberMust be a number
minlengthMinimum character length
maxlengthMaximum character length
minMinimum numeric value
maxMaximum numeric value

Custom Validation

$.validator.addMethod("phone", function(value) {
    return /^\d{10}$/.test(value);
}, "Please enter a valid 10-digit phone number");

Validate on Submit

if ($("form").valid()) {
    // Form is valid
    $("form").submit();
}

Highlighting Errors

$("form").validate({
    highlight: function(element) {
        $(element).addClass("error");
    },
    unhighlight: function(element) {
        $(element).removeClass("error");
    }
});

Mini Practice

  1. Validate a form with required fields
  2. Add email validation
  3. Create a custom validation rule
  4. Style error messages

Up Next

Continue with Forms — working with forms in jQuery.

Related Topics

Frequently Asked Questions about Validation

What is Validation in jQuery?

Validation is a fundamental concept in jQuery. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Validation?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Validation.

Why is Validation important in jQuery?

Validation is essential for jQuery development. Understanding this concept will help you write better code and solve real-world problems more effectively.