JavaScript

coding learning websites codepractice

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 Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Web Validation API


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.

What Is the Web Validation API?

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.

Why Validation Is Important

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:

  1. HTML (Built-in) Validation — done automatically by the browser using HTML attributes.

  2. JavaScript Validation — controlled using the Web Validation API.

Built-in HTML Validation Attributes

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.

Using the Validation API in JavaScript

JavaScript gives more control using methods and properties of the Validation API.

Common Properties and Methods:

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.

Example: Basic Validation Check

<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.

Using reportValidity()

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.

Setting Custom Error Messages

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.

Checking the validity object

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.

Real Example: Registration Form

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.

Summary of the Tutorial

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.


Practice Questions

  1. 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.

  2. 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.

  3. Build a signup form with password and confirm password fields. Use setCustomValidity() to show a custom error if the passwords do not match.

  4. Create a form with an input field that accepts only 10-digit mobile numbers using the pattern attribute and validate it with JavaScript.

  5. Write JavaScript code that uses reportValidity() to display the browser’s built-in validation messages when a required field is missing.

  6. Make a form that checks the length of a username. If it’s less than 4 characters, display a custom message using setCustomValidity().

  7. 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.

  8. Build a registration form with multiple fields and prevent submission until all required inputs are filled correctly using checkValidity().

  9. 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.

  10. Create a feedback form that uses reportValidity() to trigger the browser’s validation messages when the submit button is clicked without filling required fields.


JavaScript

online coding class codepractice

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 Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top