Written by: Geoffrey Callaghan

How To Do Form Validation With Validator.js

How do form validation with validator.js

In this tutorial, we’ll show you how to do form validation using Validator.js for client-side validation and FabForm.io as the form backend service for handling form submissions.

Prerequisites:

  1. Basic knowledge of HTML, JavaScript.

Step 1: Set Up Your HTML Form

Create a new HTML file (e.g., index.html) and set up a basic form. Include the necessary HTML structure and form elements.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Form Validation with Validator.js and FabForm.io</title>
</head>
<body>

  <h1>Contact Us</h1>

  <form id="contactForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <label for="message">Message:</label>
    <textarea id="message" name="message" required></textarea>

    <button type="submit">Submit</button>
  </form>

  <script src="https://cdn.jsdelivr.net/npm/validator@13.6.0"></script>
  <script src="main.js"></script>

</body>
</html>

Step 2: Implement Client-Side Validation with Validator.js

Create a new JavaScript file (e.g., main.js) to handle client-side validation using Validator.js.

document.addEventListener('DOMContentLoaded', () => {
  const form = document.getElementById('contactForm');

  form.addEventListener('submit', async (event) => {
    event.preventDefault();

    // Validate form fields
    const name = form.querySelector('#name').value;
    const email = form.querySelector('#email').value;
    const message = form.querySelector('#message').value;

    if (!validator.isLength(name, { min: 2, max: undefined })) {
      alert('Please enter a valid name (at least 2 characters).');
      return;
    }

    if (!validator.isEmail(email)) {
      alert('Please enter a valid email address.');
      return;
    }

    if (!validator.isLength(message, { min: 10, max: undefined })) {
      alert('Please enter a message with at least 10 characters.');
      return;
    }

    // If all validations pass, submit the form
    const formData = new FormData(form);

    try {
      const response = await fetch('https://fabform.io/f/YOUR_FORM_ENDPOINT', {
        method: 'POST',
        body: formData,
      });

      if (response.ok) {
        alert('Form submitted successfully!');
        form.reset();
      } else {
        alert('Error submitting form. Please try again later.');
      }
    } catch (error) {
      console.error('Error:', error);
      alert('An unexpected error occurred. Please try again later.');
    }
  });