-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
Form validation is one of the most common tasks in web development. It ensures users enter correct and complete data before submitting a form. The Web Validation API in JavaScript helps you easily check and control form inputs without needing external libraries.
Let’s explore how it works and how you can use it effectively.
The Web Validation API is a built-in browser feature that helps you validate user input in forms.
It checks whether the data entered in a form field matches the rules defined in HTML (like required
, type
, pattern
, etc.).
This API lets you:
Test whether a field’s value is valid.
Check if required fields are filled.
Display custom error messages.
Prevent form submission if validation fails.
Form validation:
Prevents incorrect or incomplete data.
Improves user experience by giving instant feedback.
Reduces server errors.
Enhances security by blocking invalid input.
There are two types of validation:
HTML (Built-in) Validation — done automatically by the browser using HTML attributes.
JavaScript Validation — controlled using the Web Validation API.
Before we get to JavaScript, you should know these HTML attributes that work with the validation API:
Attribute | Description |
---|---|
required |
Makes input mandatory. |
type |
Defines expected input type (e.g., email , number ). |
pattern |
Defines a regex pattern to match input. |
min , max |
Sets numeric range limits. |
minlength , maxlength |
Controls text length. |
step |
Defines step interval for numbers. |
Example:
<form>
<input type="email" required>
<input type="number" min="18" max="60">
<button>Submit</button>
</form>
Here, the browser automatically checks if the email is valid and the number is between 18 and 60 before submission.
JavaScript gives more control using methods and properties of the Validation API.
Method / Property | Description |
---|---|
checkValidity() |
Returns true if the field is valid. |
reportValidity() |
Shows browser’s default error message. |
setCustomValidity(message) |
Sets a custom validation message. |
validity |
Returns an object with detailed validation states. |
willValidate |
Returns true if an element will be validated. |
<form id="myForm">
<input type="text" id="name" required placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById("myForm");
const nameInput = document.getElementById("name");
form.addEventListener("submit", function(event) {
// Prevent form submission
event.preventDefault();
// Check if input is valid
if (nameInput.checkValidity()) {
alert("Form submitted successfully!");
} else {
alert("Please enter your name before submitting.");
}
});
</script>
Explanation:
The checkValidity()
method checks whether the field passes HTML validation rules.
If it’s invalid, the message appears and submission is stopped.
reportValidity()
checks validity and automatically shows the browser’s default message.
<form id="loginForm">
<input type="email" id="email" required placeholder="Enter your email">
<button type="submit">Login</button>
</form>
<script>
const form = document.getElementById("loginForm");
form.addEventListener("submit", function(e) {
e.preventDefault();
// Show built-in validation error message
if (!form.reportValidity()) {
console.log("Form is invalid");
return;
}
console.log("Form is valid");
});
</script>
Tip: reportValidity()
is helpful when you want to trigger the browser’s message automatically.
You can create custom validation messages using setCustomValidity()
.
<form id="ageForm">
<input type="number" id="age" min="18" max="60" required placeholder="Enter your age">
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById("ageForm");
const ageInput = document.getElementById("age");
form.addEventListener("submit", function(e) {
e.preventDefault();
// Custom message if under 18
if (ageInput.value < 18) {
ageInput.setCustomValidity("You must be at least 18 years old.");
} else if (ageInput.value > 60) {
ageInput.setCustomValidity("Maximum allowed age is 60.");
} else {
ageInput.setCustomValidity(""); // Clear any previous message
}
// Show error message or submit
if (form.checkValidity()) {
alert("Form submitted successfully!");
} else {
form.reportValidity();
}
});
</script>
Explanation:
setCustomValidity()
defines a personalized error.
When you pass an empty string (""
), it clears previous custom messages.
Each input field has a validity
property that contains details about what kind of validation failed.
<form id="userForm">
<input type="email" id="userEmail" required>
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById("userForm");
const email = document.getElementById("userEmail");
form.addEventListener("submit", function(e) {
e.preventDefault();
const validity = email.validity;
// Check specific conditions
if (validity.valueMissing) {
alert("Email is required!");
} else if (validity.typeMismatch) {
alert("Please enter a valid email address!");
} else {
alert("Email looks good!");
}
});
</script>
Explanation:validity
returns a set of boolean properties like:
valueMissing
typeMismatch
tooLong
tooShort
patternMismatch
rangeUnderflow
rangeOverflow
These let you handle validation more precisely.
Here’s a mini project that puts it all together.
<form id="registerForm">
<label>Email:</label>
<input type="email" id="email" required><br><br>
<label>Password:</label>
<input type="password" id="password" minlength="6" required><br><br>
<label>Age:</label>
<input type="number" id="age" min="18" max="60" required><br><br>
<button type="submit">Register</button>
</form>
<script>
const form = document.getElementById("registerForm");
form.addEventListener("submit", function(e) {
e.preventDefault();
const email = document.getElementById("email");
const password = document.getElementById("password");
const age = document.getElementById("age");
// Custom validation for password
if (password.value.length < 6) {
password.setCustomValidity("Password must be at least 6 characters long.");
} else {
password.setCustomValidity("");
}
// Check validity and show feedback
if (form.checkValidity()) {
alert("Registration successful!");
} else {
form.reportValidity();
}
});
</script>
Explanation:
Validates email format, password length, and age range.
Displays friendly custom messages.
Prevents form submission until all inputs are valid.
The Web Validation API provides developers full control over how forms are validated and how messages are displayed. It works alongside HTML validation rules to make forms more user-friendly and secure.
Key Takeaways:
Use checkValidity()
to test input fields.
Use reportValidity()
to display default messages.
Use setCustomValidity()
for custom error messages.
Access validity
for detailed validation checks.
Always combine HTML attributes with JavaScript for best results.
Create a form with a required email field. Use the Validation API to prevent form submission if the field is empty and show a custom alert message.
Write a script that checks if the age entered in a number input is between 18 and 60 using checkValidity()
and displays a message accordingly.
Build a signup form with password and confirm password fields. Use setCustomValidity()
to show a custom error if the passwords do not match.
Create a form with an input field that accepts only 10-digit mobile numbers using the pattern
attribute and validate it with JavaScript.
Write JavaScript code that uses reportValidity()
to display the browser’s built-in validation messages when a required field is missing.
Make a form that checks the length of a username. If it’s less than 4 characters, display a custom message using setCustomValidity()
.
Use the validity
object to check if a user has entered an invalid email format and show a specific error message in an alert box.
Build a registration form with multiple fields and prevent submission until all required inputs are filled correctly using checkValidity()
.
Write code that validates a numeric field to ensure the entered number is not greater than 100. Show a warning if it exceeds the limit.
Create a feedback form that uses reportValidity()
to trigger the browser’s validation messages when the submit button is clicked without filling required fields.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts