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.
Validate a form before submitting.
✍️ 3 exercises + code challenge in this lessonUse 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.
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.
<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>
Check what you learned in “jQuery Form Validation”.
Stop the form from submitting.
$("form").submit(function (e) { e.(); });
Which jQuery method adds a CSS class to show an error?
If the #email input is empty, add the class "error" to it. Run the check on page load.
Free sign-in required · Google login available
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