1.0.2 • Published 5 years ago

@alaneicker/js-form-validator v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

JavaScript Form Validator

A simple utility for managing form validation.

Installing the From Validator

Depending on your permissions, you may need to run the install command with sudo.

npm install @alaneicker/js-form-validator

Form Markup

<form id="login-form" novalidate>

  <ul id="error-summary"></ul>
    
  <label for="username"><span>*</span> Username</label>
  <input type="text" name="username" id="username">
  <ul data-error-for="username"></ul> <!-- error container -->
  
  <label for="password"><span>*</span> Password</label>
  <input type="text" name="password" id="password">
  <ul data-error-for="password"></ul> <!-- error container -->
  
  <button type="submit">Log In</button>
  
</form>

Note: The error containers below the form fields are not required unless using the ErrorMessageRouter.

Import the FormValidator, ErrorMessageRouter and Optional Utilities

Script tage on page

<script src="node_modules/@alaneicker/js-form-validator/dist/index.min.js"></script>

CommonJS

const formValidator = require('@alaneicker/js-form-validator');

ES6 Import

import { FormValidator, ErrorMessageRouter, formToJson } from '@alaneicker/js-form-validator';

Set the Form's Validation Rules

const addUserFormRules = {
  first_name: [
    {
      validator: 'required',
      message: 'First name is required',
    },
  ],
  last_name: [
    {
      validator: 'required',
      message: 'Last name is required',
    },
  ],
};

Validation on Submit

document.querySelector('#add-user').onsubmit = e => {
    e.preventDefault();
    
    const formData = formToJson(new FormData(addUserForm));
    const validationResponse = addUserFormValidator.validate(formData);
    const errorMessageRouter = new ErrorMessageRouter(addUserForm, validationResponse.data);
    
    errorMessageRouter
      .setInputErrors()
      .setErrorSummary(addUserErrorSummary);
};

Validation on Input

const formValidator = new FormValidator(loginFormRules);
const form = document.querySelector('#login');
const inputs = form.querySelectorAll('.input');

[].forEach.call(inputs, input => {
    input.addEventListener('input', e => {
      const inputData = { [e.target.name]: e.target.value };
      const validationResponse = formValidator.validate(inputData);

      if (typeof validationResponse !== 'undefined') {
        const errorMessageRouter = new ErrorMessageRouter(form, validationResponse.data);
        
        errorMessageRouter.setInputErrors();
      }
    });
});

Adding a Custom Validators

const formValidator = new FormValidator(loginFormRules);

formValidator.addValidators({
    confirmPassword(value) {
        return value === formData.password;
    }
    ...
});

Note: Be sure to add a validation rule for your custom validator.

Validation Response Object

The FormValidator.validate() API returns a validation response object containing validation data associated with each form field from the original form data object.

Note: Only form fields with errors return an message property.

{
   "totalErrors":2,
   "data":{
      "first_name":{
         "errors":1,
         "results":[
            {
               "required":"invalid",
               "message":"First name is required"
            }
         ]
      },
      "last_name":{
         "errors":1,
         "results":[
            {
               "required":"valid"
            }
         ]
      }
   }
}

API

validate

Takes 1 required argument.

  1. Type: object
FormValidator.validate(formData)

ErrorMessageRouter

You can use the validation response to set your own custom error messaging, or you use the ErrorMessageRouter class to handle the error messaging automagically.

For each of you inputs, add an error message container.

<input type="text" name="first_name" id="first_name">
<ul class="error-container" data-error-for="first_name"></ul>

Once your form has validated and returns a response, initialize the ErrorMessageRouter class and call the setErrors() method.

const addUserForm = document.querySelector('#add-user');
const validationResponse = addUserFormValidator.validate(formData); 
const isValid = validationResponse.errors === 0;

(!isValid && new ErrorMessageRouter(addUserForm, validationResponse.data).setInputErrors());

That's it! The ErrorMessageRouter will find the container associated with the error and append the appropriate message text.

API

constructor

Takes 2 required arguments.

  1. Type: object HTMLFormElement
  2. Type: object
const validationResponse = addUserFormValidator.validate(formData);

const errorMessageRouter = new ErrorMessageRouter(
    document.querySelector('#my-form'),
    validationResponse.data
);

setInputErrors

Uses the valiadtion data object to set error messages for individual input fields.

errorMessageRouter.setInputErrors();

setErrorSummary

Uses the valiadtion data object to set an error summary listing all errors for a form.

<ul id="error-summary" class="error-summary"></ul>
const errorSummary = document.querySelector('#error-summary');
errorMessageRouter.setErrorSummary(errorSummary);
1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago