JQuery Form Validation Practical Guide

What Is a Form?
A form refers to any screen on a website where users enter information.
Common examples include:
Login
Sign up
Create a post
Add a comment
Contact form
Place an order
It's essential to verify that user-entered values are correct.
This process is called form validation.
Why Is Form Validation Necessary?
Consider a scenario where a user clicks the sign-up button without entering a name.
If there's no validation:
Members with missing names
Members with incorrect email addresses
Members with no passwords
could be created. Therefore, input values must be checked before sending data to the server.
Preparation for Practice
First, create the following HTML:
<form id="joinForm">
<input type="text" id="name" placeholder="Name">
<br><br>
<input type="text" id="email" placeholder="Email">
<br><br>
<input type="password" id="password" placeholder="Password">
<br><br>
<input type="password" id="password2" placeholder="Confirm Password">
<br><br>
<input type="checkbox" id="agree">
I agree to the terms
<br><br>
<button type="submit">
Sign Up
</button>
</form>
submit() Event
Executes when the form is submitted.
$("#joinForm").submit(function(){
alert("Form submitted");
});
Clicking the sign-up button triggers this event.
Preventing Default Submission
In form validation, you must prevent submission if data is invalid.
$("#joinForm").submit(function(e){
e.preventDefault();
});
You can also use:
return false;
to stop the submission.
Getting Input Values
Use val() to retrieve input values.
var name=$("#name").val();
console.log(name);
This is one of the most commonly used functions in sign-up forms.
Checking for Empty Values
if($("#name").val()==""){
alert("Please enter your name.");
return false;
}
An alert appears if nothing is entered.
Using trim()
You must also check for spaces only.
if($.trim($("#name").val())==""){
alert("Please enter your name.");
}
The trim() function removes leading and trailing spaces.
For example:
" "
is treated as an empty value.
Moving the Cursor with focus()
You can move the cursor to the invalid field using focus().
$("#name").focus();
This is nearly essential in sign-up forms.
Email Validation
Basic check:
if($("#email").val()==""){
alert("Please enter your email.");
}
However, this alone is insufficient.
Email Format Validation
You can use regular expressions to check the format.
var email=$("#email").val();
var reg=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if(!reg.test(email)){
alert("Invalid email format.");
}
This is the most commonly used method in real-world applications.
Password Length Check
if($("#password").val().length<8){
alert("Password must be at least 8 characters.");
}
It's common to check for minimum length for security reasons.
Password Confirmation
if(
$("#password").val()
!=
$("#password2").val()
){
alert("Passwords do not match.");
}
This is a required feature in sign-up forms.
Checkbox Validation
Check if the terms agreement checkbox is selected:
if(
!$("#agree").is(":checked")
){
alert("Please agree to the terms.");
}
The form won't submit if not checked.
Allowing Only Numbers
You can use regular expressions to allow only numbers.
var phone=$("#phone").val();
var reg=/^[0-9]+$/;
if(!reg.test(phone)){
alert("Please enter only numbers.");
}
This is commonly used for phone number inputs.
Character Limit
if($("#memo").val().length>100){
alert("Please enter 100 characters or less.");
}
This feature is frequently used in post creation forms.
Real-Time Validation During Input
You can perform validation while the user types using the keyup event.
$("#password").keyup(function(){
if(
$(this).val().length<8
){
$("#msg").text(
"Enter at least 8 characters."
);
}
});
This is a common approach in modern websites.
Performing All Validations at Once
$("#joinForm").submit(function(e){
if($.trim($("#name").val())==""){
alert("Please enter your name.");
$("#name").focus();
return false;
}
if($("#email").val()==""){
alert("Please enter your email.");
$("#email").focus();
return false;
}
if($("#password").val().length<8){
alert("Password must be at least 8 characters.");
$("#password").focus();
return false;
}
});
Real-world applications often follow this structure.
Real-World Example 1
ID duplicate check button:
$("#checkBtn").click(function(){
var id=$("#userid").val();
if(id==""){
alert("Please enter an ID.");
}
});
This is often used with AJAX in subsequent lessons.
Real-World Example 2
Password strength indicator:
$("#password").keyup(function(){
if(
$(this).val().length>=8
){
$("#result").text("Available");
}
});
Real-World Example 3
Highlighting required fields:
$("input").blur(function(){
if(
$(this).val()==""){
$(this).css(
"border",
"2px solid red"
);
}
});
Unfilled fields are highlighted in red.
Real-World Example 4
Selecting all checkboxes:
$("#all").click(function(){
$("input[type=checkbox]")
.prop(
"checked",
$(this).prop("checked")
);
});
This feature is commonly used in shopping cart systems.
Common Mistakes for Beginners
Mixing val() and text()
For input fields:
.val()
For regular tags:
.text()
should be used.
Forgetting to Use trim()
If only spaces are entered, validation may pass.
Always use trim() for better accuracy.
Omitting return false
If you forget this, the form will submit even after validation checks.
This can lead to invalid data being sent to the server.
Practice Assignments
Assignment 1
Create a sign-up process that won't work if the name field is empty.
Assignment 2
Implement email format validation.
Assignment 3
Check that passwords are at least 8 characters long.
Assignment 4
Display an alert if password confirmation doesn't match.
Assignment 5
Prevent sign-up if the terms agreement checkbox isn't checked.
Key Takeaways
Form validation must be performed before sending data to the server.
val() retrieves input values.
trim() removes whitespace from strings.
focus() moves the cursor to invalid fields.
submit() executes when a form is submitted.
Regular expressions can validate email and numeric formats.
is(':checked') checks checkbox selection status.
In real-world applications, multiple validations are performed sequentially before sending data to the server.
Conclusion
This lesson covered essential form validation techniques used in sign-up and login screens.
Validating user input improves user experience while preventing invalid data from reaching your server.
Especially submit(), val(), trim(), focus(), and regular expressions are core functions used in nearly all projects, so practicing with various examples is recommended.
In the next lesson, we'll explore AJAX basics, learning how to exchange data with a server without refreshing the page.
FAQ
Why is form validation important?
Form validation ensures user input is correct before sending to the server, preventing errors and improving user experience.
What does val() do in JQuery?
val() retrieves the value of an input field, which is essential for form validation checks.
Korean Source
This article is an English localization of a Korean-language report from BlogScore. Original: [Jquery 강좌] 8강 폼(Form) 검증 실전