Blog>
Snippets

Custom Form Validation Plugin

Walk through creating a form validation plugin that provides a simple way to define and show validation rules and messages for form inputs.
<form id="myForm">
  <!-- Input fields with data-validation and data-error attributes -->
  <input type="text" name="username" data-validation="required" data-error="Username is required" />
  <input type="email" name="email" data-validation="email" data-error="Please enter a valid email" />
  <!-- Submit button -->
  <button type="submit">Submit</button>
  <!-- Place for validation messages -->
  <div id="validationErrors"></div>
</form>
HTML structure for a form with data attributes for validation rules and error messages.
/* CSS for validation errors */
.validation-error {
  color: red;
  margin: 5px 0;
}
CSS styling for the error messages displayed by the validation plugin.
document.addEventListener('DOMContentLoaded', function () {
  var form = document.getElementById('myForm');
  var validationErrorsDiv = document.getElementById('validationErrors');

  // Validation logic
  var validators = {
    required: function (value) { return value !== ''; },
    email: function (value) { return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value); }
  };

  // Handle form submit
  form.addEventListener('submit', function (event) {
    var isValid = true;
    validationErrorsDiv.innerHTML = '';
    
    Array.from(form.elements).forEach(function (input) {
      var validationType = input.getAttribute('data-validation');
      if (validationType && !validators[validationType](input.value)) {
        isValid = false;
        var errorMessage = input.getAttribute('data-error');
        var errorDiv = document.createElement('div');
        errorDiv.textContent = errorMessage;
        errorDiv.classList.add('validation-error');
        validationErrorsDiv.appendChild(errorDiv);
      }
    });

    if (!isValid) {
      event.preventDefault();
    }
  });
});
JavaScript code that adds event listeners to validate the form fields against the specified validators when the form is submitted.