Form Validation in JavaScript – Input Handling and Validation
Quick Answer: Form validation checks user input before an application accepts it. JavaScript helps us check required fields, email addresses, phone numbers and other values. We should combine HTML validation, JavaScript checks and server-side validation.
1. Why Do We Need Form Validation?
Imagine a school receives 1,000 online admission applications. Every parent enters student details through a website.
What happens when someone enters an invalid email address? What happens when someone leaves the student's name empty?
Without validation, incomplete information can reach the application. Let's first see what happens without JavaScript validation.
Without JavaScript Validation
Example 1: A basic school admission form
This example collects student details without checking their values.
<label for="studentName">Student name</label>
<input id="studentName">
<label for="email">Parent email</label>
<input id="email">
<label for="phone">Parent phone</label>
<input id="phone">
<button id="submitAdmission">
Submit application
</button>
<script>
document.getElementById("submitAdmission")
.addEventListener("click", function () {
console.log("Admission application submitted");
});
</script>
Possible output
Admission application submitted
This works, but it accepts empty and incorrect values.
What Goes Wrong?
- Student names can be empty.
- Parent email addresses can contain invalid values.
- Phone numbers can contain letters or incorrect lengths.
- Staff may need to contact parents for missing details.
- Incorrect data can affect later application steps.
Now think about 1,000 applications. Checking every record manually becomes difficult.
With JavaScript Validation
We can check each field before accepting the application. The same school example now has clear rules.
Example 2: Validation rules for admission details
function validateAdmission(student) {
const errors = [];
if (!student.name.trim()) {
errors.push("Student name is required.");
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(student.email)) {
errors.push("Enter a valid email address.");
}
if (!/^[6-9]\d{9}$/.test(student.phone)) {
errors.push("Enter a valid 10-digit phone number.");
}
return errors;
}
const student = {
name: "Priya Sharma",
email: "parent@example.com",
phone: "9876543210"
};
const errors = validateAdmission(student);
if (errors.length === 0) {
console.log("Application details are valid.");
} else {
console.log(errors);
}
Expected output
Application details are valid.
The function returns an empty list when every check passes.
| Without validation | With validation |
|---|---|
| Empty names are accepted. | Required names are checked. |
| Email values are not checked. | Email format is checked. |
| Phone values are accepted as entered. | Phone format is checked. |
| Errors appear later. | Errors appear before submission. |
| Staff must identify missing details. | Users can correct details earlier. |
Important Terms to Remember
- Form: A group of fields that collects user information.
- Input handling: Reading and processing values entered by users.
- Validation: Checking whether an entered value follows a rule.
- Event: Something that happens, such as typing or submitting.
- Regular expression: A pattern used to check text values.
- Client-side validation: Checks performed inside the user's browser.
- Server-side validation: Checks performed by the backend application.
2. How Does Form Validation Work?
A browser collects the values entered by a parent. JavaScript reads those values and checks each rule.
Only valid details should continue to the next application step.
The diagram follows admission details from user input through checks and the final decision.
3. Build a Complete Admission Form
Let's build a small form with four fields. We will check each value before accepting submission.
The example uses plain HTML, CSS and JavaScript. No external library is needed.
Step 1: Create the HTML Fields
Example 3: Admission form structure
<form id="admissionForm" novalidate>
<label for="studentName">Student name</label>
<input id="studentName" name="studentName"
type="text" required>
<small id="nameError" aria-live="polite"></small>
<label for="parentEmail">Parent email</label>
<input id="parentEmail" name="parentEmail"
type="email" required>
<small id="emailError" aria-live="polite"></small>
<label for="parentPhone">Parent phone</label>
<input id="parentPhone" name="parentPhone"
type="tel" required>
<small id="phoneError" aria-live="polite"></small>
<label for="studentAge">Student age</label>
<input id="studentAge" name="studentAge"
type="number" min="3" max="18" required>
<small id="ageError" aria-live="polite"></small>
<button type="submit">Submit application</button>
<p id="formMessage" aria-live="polite"></p>
</form>
Each field has a matching label and error message area. The novalidate attribute disables the browser's automatic submit blocking.
Step 2: Read and Check the Values
We will keep validation rules inside separate functions. This makes each rule easier to test.
Example 4: JavaScript validation functions
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const phonePattern = /^[6-9]\d{9}$/;
function validateName(value) {
return value.trim().length >= 2
? ""
: "Enter a name with at least 2 characters.";
}
function validateEmail(value) {
return emailPattern.test(value.trim())
? ""
: "Enter a valid email address.";
}
function validatePhone(value) {
return phonePattern.test(value.trim())
? ""
: "Enter a valid 10-digit phone number.";
}
function validateAge(value) {
const age = Number(value);
return Number.isInteger(age) && age >= 3 && age <= 18
? ""
: "Enter an age between 3 and 18.";
}
Each function returns an empty string when its value is valid. Otherwise, it returns a message.
Step 3: Display Errors and Handle Submission
Now we connect the rules to the form. We also stop invalid submissions.
Example 5: Complete submission handling
const form = document.getElementById("admissionForm");
const fields = [
{
input: document.getElementById("studentName"),
error: document.getElementById("nameError"),
validate: validateName
},
{
input: document.getElementById("parentEmail"),
error: document.getElementById("emailError"),
validate: validateEmail
},
{
input: document.getElementById("parentPhone"),
error: document.getElementById("phoneError"),
validate: validatePhone
},
{
input: document.getElementById("studentAge"),
error: document.getElementById("ageError"),
validate: validateAge
}
];
function checkField(field) {
const message = field.validate(field.input.value);
field.error.textContent = message;
field.input.setAttribute("aria-invalid", String(Boolean(message)));
return message === "";
}
fields.forEach(function (field) {
field.input.addEventListener("blur", function () {
checkField(field);
});
field.input.addEventListener("input", function () {
if (field.error.textContent) {
checkField(field);
}
});
});
form.addEventListener("submit", function (event) {
event.preventDefault();
const results = fields.map(checkField);
const isValid = results.every(Boolean);
const message = document.getElementById("formMessage");
if (isValid) {
message.textContent = "All details are valid. Ready to submit.";
} else {
message.textContent = "Please correct the highlighted fields.";
}
});
This example checks every field when the user submits. It also checks fields after focus leaves them.
Important: This example demonstrates browser-side validation. A real application must send valid data to a backend endpoint and validate it again there.
4. Understand Input Events
JavaScript can respond to different events during data entry. Each event has a different purpose.
Runs whenever the field value changes. Useful for live feedback.
Runs when a changed value is committed. Useful for selected values.
Runs when the user leaves a field. Useful for field-level checks.
Runs when the user submits the form. Useful for final validation.
See How Field States Change
The following view shows sample admission values and their validation states.
The field states highlight separate checks for required values, email, phone and age.
5. HTML Validation Attributes
HTML already provides useful validation features. Use them before adding custom JavaScript rules.
| Attribute | Purpose | Example |
|---|---|---|
required |
Requires a value. | Name field |
type="email" |
Checks basic email format. | Email field |
minlength |
Sets the minimum text length. | Minimum 2 characters |
maxlength |
Sets the maximum text length. | Maximum 60 characters |
min and max |
Set numeric limits. | Age from 3 to 18 |
pattern |
Checks a value against a pattern. | Phone number |
Use the Browser Constraint Validation API
The browser exposes methods that help us check HTML validation rules.
Example 6: Check a field using checkValidity
const emailInput = document.getElementById("parentEmail");
if (emailInput.checkValidity()) {
console.log("Email field is valid.");
} else {
console.log(emailInput.validationMessage);
}
Example output
Email field is valid.
checkValidity()returns true when the field passes its constraints.reportValidity()checks the field and displays browser feedback.setCustomValidity()sets a custom validation message.
6. Common Validation Mistakes
Mistake 1: Checking Only Whether a Field Is Empty
A non-empty email can still have an invalid format. Check the actual rule, not just the presence of text.
Mistake 2: Forgetting to Trim Input
Spaces can make an apparently filled name invalid. Use trim() before checking text values.
Mistake 3: Using One Large Validation Function
One large function becomes harder to test. Keep each field rule in a separate function.
Mistake 4: Using innerHTML for Error Messages
Never place untrusted user input inside HTML markup. Use textContent for plain messages.
Mistake 5: Trusting Browser Validation Alone
Users can change browser requests or disable JavaScript. Always validate data on the server.
Mistake 6: Showing Errors Without Accessibility Support
Screen readers need clear error information. Use labels, aria-invalid and live error regions.
7. Client-Side and Server-Side Validation
Both checks are important, but they protect different parts of the application.
- Runs in the browser.
- Gives quick feedback.
- Improves the user experience.
- Can be bypassed.
- Runs on the backend.
- Protects stored data.
- Checks requests independently.
- Must not trust browser results.
A secure application checks data again before saving it. The backend should enforce the actual business rules.
8. How This Comes Up in Interviews
Question 1: What Is Form Validation?
Strong answer: Form validation checks whether user input follows required rules. I use HTML constraints for basic checks and JavaScript for custom rules. I also validate every request on the backend.
Question 2: What Is the Difference Between input and change?
Strong answer: The input event fires whenever the value changes. The change event fires when the value is committed. I choose the event based on the feedback needed.
Question 3: Can Client-Side Validation Protect an Application?
Strong answer: It improves the user experience, but it is not a security boundary. Users can bypass browser checks. The backend must validate every incoming request.
Question 4: How Do You Show Accessible Validation Errors?
Strong answer: I connect labels with their inputs. I set aria-invalid when a value is incorrect. I also announce useful messages with an aria-live region.
Question 5: Why Should We Use textContent?
Strong answer: textContent treats the message as plain text. It does not parse the value as HTML. This avoids inserting user input as markup.
9. Hands-On Practice
Beginner
- Create a student name field and make it mandatory.
- Check whether the parent email contains a valid format.
- Show an error when the phone number is empty.
Intermediate
- Validate a phone number using a regular expression.
- Show errors when a user leaves each field.
- Clear an error after the user corrects the value.
Advanced
- Build a multi-step school admission form.
- Keep entered values when moving between steps.
- Validate each step before allowing the next step.
- Submit the final data to a backend endpoint.
- Repeat all important checks on the server.
10. Best Practices to Follow
- Use HTML validation for simple field rules.
- Use JavaScript for custom validation and feedback.
- Keep validation functions small and reusable.
- Trim text before checking it.
- Show clear messages near the related fields.
- Use textContent when displaying user-related messages.
- Support keyboard users and screen readers.
- Validate every request again on the backend.
- Do not expose internal system details in error messages.
11. Next Steps and Community
Try building the school admission form yourself. Add new fields and write separate validation rules for each one.
Explore the official guides:
Share your implementation and discuss better validation approaches with the Upgradix community.
Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.