jQuery Form Validation

Validate a form before submitting.

✍️ 3 exercises + code challenge in this lesson

Use the submit event, read values with .val(), and call e.preventDefault() when something is wrong.

Show errors next to each field and add an error class for styling.

Key Takeaways: jQuery Form Validation

Mastering jQuery Form Validation helps you write clean and reliable jQuery code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

jQuery Form Validation Code Example

jQuery
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<style> .error { border: 2px solid #DC2626; } .msg { color: #DC2626; font-size: 13px; } </style>
<form id="f">
  <input id="email" placeholder="Email"> <span class="msg" id="emailMsg"></span><br><br>
  <input id="age" type="number" placeholder="Age"> <span class="msg" id="ageMsg"></span><br><br>
  <button>Register</button>
</form>
<p id="ok" style="color:#16A34A"></p>

<script>
  $("#f").submit(function (e) {
    e.preventDefault();
    let valid = true;
    $(".msg").text(""); $("input").removeClass("error"); $("#ok").text("");

    if (!/^\S+@\S+\.\S+$/.test($("#email").val())) {
      $("#email").addClass("error"); $("#emailMsg").text("Enter a valid email"); valid = false;
    }
    if ($("#age").val() < 18) {
      $("#age").addClass("error"); $("#ageMsg").text("Must be 18+"); valid = false;
    }
    if (valid) $("#ok").text("Registered successfully!");
  });
</script>
Free sign-in required · Google login available

jQuery Form Validation Practice Exercises

Check what you learned in “jQuery Form Validation”.

/ 3 solved
Fill in the blank

Stop the form from submitting.

$("form").submit(function (e) { e.(); });
✓ Correct! Not quite. Try again.
Multiple choice

Which jQuery method adds a CSS class to show an error?

✓ Correct! Not quite. Try again.
Code challenge

If the #email input is empty, add the class "error" to it. Run the check on page load.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services