Learn how to Create Custom JavaScript Form Validation

Muhaymin Bin Mehmood

Muhaymin Bin Mehmood

· 5 min read
Learn how to Create Custom JavaScript Form Validation Banner Image
Learn how to Create Custom JavaScript Form Validation Banner Image

Form validation is a critical part of web development, ensuring that users provide valid and complete data before submission. While libraries like jQuery and frameworks offer built-in validation, creating custom JavaScript validation functions gives you complete control over the process. This blog covers everything you need to know to build robust custom form validation functions in JavaScript.

Table of Contents

  1. Introduction to Form Validation
  2. Why Use Custom JavaScript Validation?
  3. Types of Validation
  4. Basic Validation Concepts
  5. Steps to Create Custom Validation Functions
  6. Implementing Validation for Common Input Types
  7. Real-World Use Case: A Registration Form
  8. Benefits of Custom Form Validation
  9. Common Mistakes to Avoid
  10. Complete Validation Code
  11. FAQs

1. Introduction to Form Validation

Form validation ensures that data entered by users meets the required criteria before submission. Validation can occur on the client side (browser) or server side. Client-side validation improves user experience by providing instant feedback.

2. Why Use Custom JavaScript Validation?

  • Flexibility: Create rules tailored to your requirements.
  • Control: Customize error messages and behaviors.
  • Performance: Reduce server load with client-side validation.
  • Enhanced User Experience: Provide instant, user-friendly feedback.

3. Types of Validation

  • Required Field Validation: Ensures mandatory fields are not empty.
  • Input Format Validation: Checks formats like email or phone numbers.
  • Range Validation: Validates numbers, dates, or text within a specific range.
  • Custom Validation: Implements complex rules like password strength or username availability.

4. Basic Validation Concepts

  • Event Listeners: Attach validation functions to input fields (e.g., onblur, oninput).
  • Regex Patterns: Use regular expressions to validate text patterns like emails and phone numbers.
  • DOM Manipulation: Dynamically update the UI with error messages or styling.

5. Steps to Create Custom Validation Functions

Step 1: Identify validation requirements.
Step 2: Create reusable JavaScript functions.
Step 3: Use event listeners for real-time validation.
Step 4: Display error messages for invalid inputs.
Step 5: Prevent form submission until all validations pass.

Example:

function validateRequired(input, errorMessage) {  
  if (!input.value.trim()) {  
    showError(input, errorMessage);  
    return false;  
  }  
  clearError(input);  
  return true;  
}  

function showError(input, message) {  
  const error = document.createElement('span');  
  error.className = 'error';  
  error.innerText = message;  
  input.parentNode.appendChild(error);  
}  

function clearError(input) {  
  const error = input.parentNode.querySelector('.error');  
  if (error) {  
    input.parentNode.removeChild(error);  
  }  
}  

6. Implementing Validation for Common Input Types

1. Email Validation:

function validateEmail(input) {  
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;  
  if (!regex.test(input.value.trim())) {  
    showError(input, 'Invalid email format');  
    return false;  
  }  
  clearError(input);  
  return true;  
}

2. Password Validation:

function validatePassword(input) {  
  const regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;  
  if (!regex.test(input.value.trim())) {  
    showError(input, 'Password must be at least 8 characters, including a number, uppercase, and lowercase letter');  
    return false;  
  }  
  clearError(input);  
  return true;  
}

3. Phone Number Validation:

function validatePhone(input) {  
  const regex = /^\d{10}$/;  
  if (!regex.test(input.value.trim())) {  
    showError(input, 'Enter a valid 10-digit phone number');  
    return false;  
  }  
  clearError(input);  
  return true;  
}

7. Real-World Use Case: A Registration Form

HTML:

<form id="registrationForm">  
  <input type="text" id="name" placeholder="Name" required>  
  <input type="email" id="email" placeholder="Email" required>  
  <input type="password" id="password" placeholder="Password" required>  
  <input type="tel" id="phone" placeholder="Phone Number" required>  
  <button type="submit">Register</button>  
</form>  

JavaScript:

document.getElementById('registrationForm').addEventListener('submit', function(e) {  
  e.preventDefault();  
  const nameValid = validateRequired(document.getElementById('name'), 'Name is required');  
  const emailValid = validateEmail(document.getElementById('email'));  
  const passwordValid = validatePassword(document.getElementById('password'));  
  const phoneValid = validatePhone(document.getElementById('phone'));  

  if (nameValid && emailValid && passwordValid && phoneValid) {  
    alert('Registration Successful');  
  }  
});  

8. Benefits of Custom Form Validation

  • Customizable: Tailor validation rules to match business needs.
  • User-Friendly: Provide specific and actionable error messages.
  • Real-Time Feedback: Improve user experience with instant validation.

9. Common Mistakes to Avoid

  • Lack of Real-Time Feedback: Validate inputs as the user types.
  • Ignoring Edge Cases: Consider unusual inputs and formats.
  • Poor Error Messages: Use descriptive and helpful error messages.

10. Complete Validation Code

// Validation functions
function validateRequired(input, errorMessage) {
  if (!input.value.trim()) {
    showError(input, errorMessage);
    return false;
  }
  clearError(input);
  return true;
}

function validateEmail(input) {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!regex.test(input.value.trim())) {
    showError(input, 'Invalid email format');
    return false;
  }
  clearError(input);
  return true;
}

function validatePassword(input) {
  const regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
  if (!regex.test(input.value.trim())) {
    showError(input, 'Password must be at least 8 characters, including a number, uppercase, and lowercase letter');
    return false;
  }
  clearError(input);
  return true;
}

function validatePhone(input) {
  const regex = /^\d{10}$/;
  if (!regex.test(input.value.trim())) {
    showError(input, 'Enter a valid 10-digit phone number');
    return false;
  }
  clearError(input);
  return true;
}

// Helper functions
function showError(input, message) {
  clearError(input);
  const error = document.createElement('span');
  error.className = 'error';
  error.innerText = message;
  input.parentNode.appendChild(error);
}

function clearError(input) {
  const error = input.parentNode.querySelector('.error');
  if (error) {
    input.parentNode.removeChild(error);
  }
}

// Form submission handler
document.getElementById('registrationForm').addEventListener('submit', function (e) {
  e.preventDefault();

  const nameValid = validateRequired(document.getElementById('name'), 'Name is required');
  const emailValid = validateEmail(document.getElementById('email'));
  const passwordValid = validatePassword(document.getElementById('password'));
  const phoneValid = validatePhone(document.getElementById('phone'));

  if (nameValid && emailValid && passwordValid && phoneValid) {
    alert('Registration Successful');
  }
});

HTML Structure

For reference, here's the corresponding HTML structure:

<form id="registrationForm">
  <input type="text" id="name" placeholder="Name" required>
  <input type="email" id="email" placeholder="Email" required>
  <input type="password" id="password" placeholder="Password" required>
  <input type="tel" id="phone" placeholder="Phone Number" required>
  <button type="submit">Register</button>
</form>

11. FAQs

Q1: Why should I use custom JavaScript validation instead of HTML5 attributes?
Custom JavaScript provides flexibility and allows you to implement complex validation rules that HTML5 attributes cannot handle.

Q2: Can I combine custom validation with server-side validation?
Yes, client-side validation enhances user experience, but server-side validation ensures data integrity and security.

Q3: How do I style error messages dynamically?
Use CSS classes in conjunction with JavaScript to highlight invalid fields or display custom error messages.

Q4: What happens if JavaScript is disabled in the browser?
Without JavaScript, client-side validation won’t work. Always implement server-side validation as a fallback.

Q5: Can I reuse validation functions across multiple projects?
Yes, by writing modular and reusable code, you can easily incorporate your validation functions into other projects.

Conclusion

Creating custom JavaScript form validation functions equips you with the ability to ensure data accuracy, enhance user experience, and maintain control over your forms. By implementing robust validation logic, you provide instant feedback to users and reduce errors before data submission. Whether you're validating a simple login form or a complex registration form, mastering custom validation techniques is an essential skill for every developer.

Muhaymin Bin Mehmood

About Muhaymin Bin Mehmood

Front-end Developer skilled in the MERN stack, experienced in web and mobile development. Proficient in React.js, Node.js, and Express.js, with a focus on client interactions, sales support, and high-performance applications.

Copyright © 2025 Mbloging. All rights reserved.