npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@switch-company/form-validation

v2.1.0

Published

Extend checkvalidity of forms and trigger invalid and valid events on fields

Downloads

4

Readme

Switch - formValidation

Add custom validation and create bubbling invalid and valid events to form elements.


Constructor

new Validator( HTMLFormElement, Object )

Create a new validator instance.

  • HTMLFormElement - the form to validate
  • Object - the validator parameters

Parameters

The parameter Object contains one entry to pass custom validation rules:

  • customRules - Array of custom validation rules
  const parameters = {
    customRules: [ ... ]
  }

Custom validation rules format

A custom validation rule is an object containing two entries:

  • match: A CSS selector matching the elements that you want the validator to test
  • test: A function that will test the element
  • message: An error message to pass when the test fails (optional)

The test function must return true, false, or a custom ValidityState you want to return for this test. If the return value is false the ValidityState value will be customError. When true the test succeed, otherwise it fails.

[
  {
    // apply maxlength tests to all inputs, not only [type=number]
    // the ValidityState value will return "tooLong" if the test fails
    match: '[data-maxlength], [maxlength]',
    message: 'Too many characters',
    test: (el) => {
      const length = parseInt( el.dataset.maxlength || el.getAttribute( 'maxlength' ), 10);
      return el.value.length <= length ? true : 'tooLong';
    }
  },
  {
    // the ValidityState value will return "customError" if the test fails
    match: '[data-match]',
    test: (el) => {
      const shouldMatch = document.getElementById( el.dataset.match );
      return shouldMatch && shouldMatch.value === el.value;
    }
  }
]

Basic use

  import Validator from '@switch-company/form-validation';

  const params = {
    customRules [
      {
        match: '[data-maxlength], [maxlength]',
        message: 'Too many characters',
        test: (el) => {
          const length = parseInt( el.dataset.maxlength || el.getAttribute( 'maxlength' ), 10);
          return el.value.length <= length ? true : 'tooLong';
        }
      },
      {
        match: '[data-match]',
        test: (el) => {
          const shouldMatch = document.getElementById( el.dataset.match );
          return shouldMatch && shouldMatch.value === el.value;
        }
      }
    ]
  };

  const validator = new Validator( document.querySelector( 'form' ), params );

  validator.checkValidity(); // returns `true` or `false`

Methods

.checkValidity( HTMLElement )

Check the validity of the passed element. Defaults to the form element the validator was created on if no HTMLElement is passed.

Return true when valid, otherwise false.

  const validator = new Validator( document.querySelector( 'form' ));

  validator.checkValidity(); // returns `true` or `false` depending of the `form` validity state

  validator.checkValidity( document.querySelector( 'fieldset' )); // returns `true` or `false` depending of the `fieldset` validity state

  validator.checkValidity( document.querySelector( 'input' )); // returns `true` or `false` depending of the `input` validity state

.setValidity(Object)

Set custom error messages on the form elements by passing an object with [element name]: 'error message'. Remove all custom errors by calling it without passing anything. Usually this method is used if the backend respond with some extra errors that the front-end can't or won't handle. For custom front-end errors, use custom rules by passing them when instanciating the constructor.

  const form = document.querySelector( 'form' );
  const validator = new Validator( form );

  if(validator.checkValidity()){
    // post the data if front-end doesn't see any errors
    const backendResponse = await fetch('/endpoint', {
      method: 'POST',
      body: new FormData( form ),
    }).then(r => r.json());

    /*
    * errors object should look like this:
    * {
    *   'postal-code': 'Cannot deliver to this postal code'
    * }
    */

    if(backendResponse.errors){
      // trigger an invalid event to the listed form elements
      validator.setValidity(backendResponse.errors);
    }
  }

.fieldset( HTMLFieldsetElement )

Return the validator instance of a fieldset contained in the form. This allows you to check the validity of the fieldset.

  const validator = new Validator( document.querySelector( 'form' ));

  const fieldsetValidator = validator.fieldset( document.querySelector( 'fieldset' ));

  fieldsetValidator.checkValidity(); // returns `true` or `false`

Properties

.invalid

Return an Array of invalid fields. .checkValidity() must be called before or the property won't reflect the validity state of the form.

  const validator = new Validator( document.querySelector( 'form' ));

  validator.checkValidity();

  validator.invalid; // returns an `Array` of invalid fields

.fieldsets

Return an Array of validators instances created on the fieldsets elements contained in the form.

  const validator = new Validator( document.querySelector( 'form' ));

  validator.fieldsets; // returns an `Array` of validators

Events

Events invalid and valid are created with the CustomEvent constructor and set to bubble so there's no need to parse and bind every field. The current validityState of the field is passed in the detail object of the event.

invalid event

An invalid event is dispatched to any field failing to validate.

  const form = document.querySelector( 'form' );

  form.addEventListener( 'invalid' , e => {
    console.log( e.target ); // return the field

    console.log( e.detail.validityState ); // return the current validityState of the field
    console.log( e.detail.message ); // return the message set by the custom rule or the `.setValidity()` method
    console.log( e.detail.wasInvalid ); // return `true` if the field was invalid before calling `.checkValidity()`, `false` otherwise
    console.log( e.detail.context ); // return the HTMLElement passed to the `.checkValidity()` method or HTMLElement bond to the validator
  });

valid event

A valid event is dispatched to any field passing the validation.

  const form = document.querySelector( 'form' );

  form.addEventListener( 'valid' , e => {
    console.log( e.target ); // return the field

    console.log( e.detail.validityState ); // return the current validityState of the field
    console.log( e.detail.wasInvalid ); // return `true` if the field was invalid before calling `.checkValidity()`, `false` otherwise
    console.log( e.detail.context ); // return the HTMLElement passed to the `.checkValidity()` method or HTMLElement bond to the validator
  });