JavaScript
Form Validation



Introduction to Form Validation

Form validation ensures that users provide valid and expected input before the data is processed. In real-world applications, it's crucial to prevent incorrect or malicious data from being submitted.

There are two types of validations:

In this topic, we focus on pure JavaScript client-side validation using functions that simulate form input and logic—no HTML needed.

Example 1: Basic Required Field Check

This example demonstrates checking if the user has entered any value.


// Simulated input
const userInput = "";

// Validation function
function validateRequired(input) {
  if (input.trim() === "") {
    return "This field is required.";
  } else {
    return "Input accepted.";
  }
}

console.log(validateRequired(userInput));

Output:

This field is required.

Example 2: Validate Email Format

Let’s validate whether an input is a valid email using a basic regex.


// Simulated input
const emailInput = "user@example.com";

// Validation function
function validateEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email) ? "Valid email." : "Invalid email format.";
}

console.log(validateEmail(emailInput));

Output:

Valid email.

Question:

Why use regex instead of just checking for @ and .?

Answer: Regex ensures proper structure, avoiding common mistakes like @., user@@example, or user@.com.

Example 3: Password Length Check

Passwords should have a minimum number of characters. Here’s a validation function for that.


// Simulated input
const password = "pass123";

// Validation function
function validatePasswordLength(pwd) {
  return pwd.length >= 8
    ? "Password length is acceptable."
    : "Password must be at least 8 characters.";
}

console.log(validatePasswordLength(password));

Output:

Password must be at least 8 characters.

Example 4: Confirm Password Match

This example checks if the confirmation password matches the original password.


const password = "secret123";
const confirmPassword = "secret1234";

function validatePasswordMatch(pwd, confirmPwd) {
  return pwd === confirmPwd
    ? "Passwords match."
    : "Passwords do not match.";
}

console.log(validatePasswordMatch(password, confirmPassword));

Output:

Passwords do not match.

Example 5: Full Form Validation Simulation

This example combines all the above checks into one function to simulate a form submission check.


const formData = {
  name: "John",
  email: "john.doe@domain.com",
  password: "pass123",
  confirmPassword: "pass123"
};

function validateForm(data) {
  const errors = [];

  if (data.name.trim() === "") errors.push("Name is required.");

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(data.email)) errors.push("Invalid email format.");

  if (data.password.length < 8)
    errors.push("Password must be at least 8 characters.");

  if (data.password !== data.confirmPassword)
    errors.push("Passwords do not match.");

  return errors.length > 0 ? errors : ["Form submitted successfully!"];
}

console.log(validateForm(formData));

Output:

[
  "Password must be at least 8 characters."
]

Summary

Points to Remember



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M