Get started with validator CDN

MIT licensed

The Validator.js library is a lightweight, flexible tool for adding client-side form validation in JS.

Tags:
  • validator
  • validation
  • validate
  • sanitization
  • sanitize
  • sanitisation
  • sanitise
  • assert

Stable version

Copied!

How to start using validator CDN


<!DOCTYPE html>
<html>
<head>
  <title>Get started with validator CDN - cdnhub.io</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/validator.min.js"></script>
</head>
<body>
  <form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    <span class="error" id="nameError"></span>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    <span class="error" id="emailError"></span>

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

  <script>
    const form = document.querySelector('#myForm');
    const nameInput = document.querySelector('#name');
    const nameError = document.querySelector('#nameError');
    const emailInput = document.querySelector('#email');
    const emailError = document.querySelector('#emailError');

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

      const validator = new Validator(form, {
        formIsValid: (formData) => {
          return Validator.validateAllFields(formData);
        },
        errorClass: 'error',
        successClass: 'success'
      });

      validator.validate().then((results) => {
        if (results.isValid) {
          console.log('Form is valid');
        } else {
          console.log('Form is not valid');
          results.fields.forEach((field) => {
            if (field.valid) {
              return;
            }
            const errorElement = document.querySelector(`#${field.name}Error`);
            errorElement.textContent = field.message;
          });
        }
      });
    });
  </script>
</body>
</html>
Copied!
Copied!

All versions