Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Compiler Tools

Validations in JavaScript — Form Validation Guide

Validations

It is very important to pre-validate the forms before submission as they can have inappropriate values. JavaScript provides the facility to validate the form on the client-side so data processing will be faster than server-side validation.

Form Validations Examples

example
function validate() {
	// name can not be blank
	if( document.myForm.name.value == "" ) {
		alert( "Please enter your name!" );
		document.myForm.name.focus();
		return false;
	}
	
	// email can not be blank
	if( document.myForm.email.value == "" ) {
		alert( "Please enter your email!" );
		document.myForm.EMail.focus();
		return false;
	}
	
	// enter a password with at least 7 characters
	if( document.myForm.password.value == "" || isNaN( document.myForm.password.value ) || document.myForm.password.value.length > 7 ) {
		alert( "Please enter a password with at least 7 characters");
		document.myForm.mobile.focus();
		return false;
	}
	return( true );
}

Regex-Based Validation

Regular expressions provide powerful pattern matching for validating emails, phone numbers, URLs, and more.

Regex Validation
// Email validation
function isValidEmail(email) {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}
console.log(isValidEmail('user@example.com')); // true
console.log(isValidEmail('invalid-email'));     // false

// Phone number (10 digits)
function isValidPhone(phone) {
  return /^\d{10}$/.test(phone);
}
console.log(isValidPhone('9876543210')); // true

// Strong password: min 8 chars, uppercase, lowercase, digit, special char
function isStrongPassword(pwd) {
  return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/.test(pwd);
}
console.log(isStrongPassword('Secure@123')); // true
console.log(isStrongPassword('weak'));        // false

// URL validation
function isValidURL(url) {
  try {
    new URL(url);
    return true;
  } catch {
    return false;
  }
}
console.log(isValidURL('https://tutorialslogic.com')); // true

HTML5 Constraint Validation API

Modern browsers provide a built-in Constraint Validation API that works alongside HTML5 form attributes like required, minlength, pattern, and type.

Constraint Validation API
const form = document.getElementById('myForm');
const emailInput = document.getElementById('email');

form.addEventListener('submit', function(e) {
  e.preventDefault();

  // Check validity using built-in API
  if (!emailInput.validity.valid) {
    if (emailInput.validity.valueMissing) {
      emailInput.setCustomValidity('Email is required.');
    } else if (emailInput.validity.typeMismatch) {
      emailInput.setCustomValidity('Please enter a valid email address.');
    }
    emailInput.reportValidity();
    return;
  }

  // Clear custom message and submit
  emailInput.setCustomValidity('');
  console.log('Form is valid, submitting...');
});

// Real-time validation feedback
emailInput.addEventListener('input', function() {
  if (this.validity.valid) {
    this.classList.remove('is-invalid');
    this.classList.add('is-valid');
  } else {
    this.classList.remove('is-valid');
    this.classList.add('is-invalid');
  }
});
Key Takeaways
  • Client-side validation improves UX but never replace server-side validation - always validate on both sides.
  • Use regex patterns for email, phone, and password validation.
  • The HTML5 Constraint Validation API (validity, setCustomValidity, reportValidity) provides built-in validation without extra libraries.
  • Use event.preventDefault() to stop form submission and run your own validation logic.
  • Provide clear, specific error messages - tell users exactly what is wrong and how to fix it.
  • Real-time validation (on input event) gives immediate feedback as users type.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.