2.0.1 • Published 7 years ago

envoy-form-validation v2.0.1

Weekly downloads
4
License
MIT
Repository
github
Last release
7 years ago

Envoy Form Validation

Installation

npm install envoy-form-validation --save

or

yarn add envoy-form-validation

Description

On the websites we build, we commonly have standard forms to collect a user's name, email, phone, etc. This is a validation service built to standardize the validation and error handling for these forms.

This is a vanilla js service that supports IE11+. It requires a module bunder using Babel (this is standard in most Envoy build systems).

Basics

  • The service assumes the inputs passed are always required. You're able to specifiy otherwise by passsing required: false. To not validate the types checkbox or radio, simply do not pass a check. For other inputs, to make them not required you would (as an example) pass the following:

    {
      ...
      checks: [
        { someOtherValidation: true },
        { required: false }
        ...
      ],
    }
  • If you want the service to show error messages on sumbission, you need to add the class validate to each <input>. For radio inputs, use a wrapper around the inputs and put the validate class on the wrapper

  • Available checks are:

    CheckTypeDefault
    requiredbooleantrue
    alphabooleannull
    alphaNumericbooleannull
    checkboxbooleannull
    emailbooleannull
    maxLengthnumbernull
    minLengthnumbernull
    numericbooleannull
    phonebooleannull
    radiobooleannull

Settings

OptionTypeDefaultDescription
checksarraynullArray containing the validation checks you want to perform. Nothing is checked without passing some sort of check. For checkbox and radio, be sure to pass whether it's either (as shown in the Usage example).
customMessagesarraynullOptional, custom messaging you can use in place of the default messaging. Note Custom messaging must follow format of {type: 'valid', input: 'email', message: 'some message...'}
showErrorMessagesbooleanfalseOption for the service to automatically update and show error messages in the DOM. Note if you are not getting a message back from the service, you likely are using an input or input name not accounted for. Simply pass your needed input message

Usage:

  <form class="form" action="">
    <label for="first-name">First Name</label>
    <input class="validate form__first-name" type="text" name="first-name">
    <br>

    <label for="last-name">Last Name</label>
    <input class="validate form__last-name" type="text" name="last-name">
    <br>

    <label for="tel">Phone</label>
    <input class="validate form__tel" type="tel" name="tel">
    <br>

    <label for="email">Email</label>
    <input class="validate form__email" type="email" name="email">
    <br>

    <label for="signup">Signup For Emails?!</label>
    <input class="validate form__signup" type="checkbox" name="signup">
    <br>

    <div class="form__radio-group validate">
      <p>Preferred method of contact:</p>

      <input type="radio" id="contactChoice1" name="contact" value="email">
      <label class="form__radio" for="contactChoice1">Email</label>

      <input type="radio" id="contactChoice2" name="contact" value="phone">
      <label class="form__radio" for="contactChoice2">Phone</label>

      <input type="radio" id="contactChoice3" name="contact" value="mail">
      <label class="form__radio" for="contactChoice3">Mail</label>
    </div>
    <br>

    <a href="#" class="form__submit">Submit</button>
  </form>
  import Validation from 'envoy-form-validation';

  export default class Form {
    constructor() {
      const submit = document.querySelector('.form__submit');

      submit.addEventListener('click', (e) => {
        e.preventDefault();
        this.formHandler();
      });
    }

    formHandler() {
      // initialize instance of the Validation service
      // Pass array of inputs and the type(s) of validation you need for the input
      // The value used for the ```input``` key must match what's available from the service
      const checks = new Validation({
        showErrorMessages: true,
        checks: [
          {
            type: 'text',
            values: document.querySelectorAll('.form input[type="text"]'),
            checks: [
              { alpha: true },
              { minLength: true, length: 2 },
            ],
          },
          {
            type: 'email',
            values: document.querySelectorAll('.form input[type="email"].form__email'),
            checks: [
              { email: true },
            ],
          },
          {
            type: 'checkbox',
            values: document.querySelectorAll('.form input[type="checkbox"].form__signup'),
            checks: [
              { checkbox: true }, // enables a requirement validation
            ],
          },
          {
            type: 'tel',
            values: document.querySelectorAll('.form input[type="tel"].form__tel'),
            checks: [
              { tel: true },
            ],
          },
        ],
        customMessages: [
          {
            reason: 'invalid',
            inputName: 'email',
            message: 'Your email is 💩',
          },
          {
            reason: 'checkbox', // match to type="checkbox"
            inputName: 'signup', // match to name="yourInputsName"
            message: 'Click the ✓ ya 💩', // add your custom message
          }
        ],
      });

      // Call the validate() method
      // validate() returns a promise
      // If valid, it resolves and sends { isValid: true }
      // If false, it rejects and sends { errorData: [array], isValid: boolean }
      checks.validate()
        .then(data => {
          console.log(data);
          // submit form...
        })
        .catch(error => {
          console.log(error);
          // show messages, handle errors
        });
    }
  }
  new Form();

Issues / Requests

You can report any issues, or make feature requests here