Lightweight Flexible Form Validation Engine – simpower-validation

Category: Form , Javascript | November 13, 2023
Author:Kallenju
Views Total:24 views
Official Page:Go to website
Last Update:November 13, 2023
License:MIT

Preview:

Lightweight Flexible Form Validation Engine – simpower-validation

Description:

A lightweight, flexible, simple-to-use, developer-friendly form validation library written in PURE JavaScript.

Unlike other form validation libraries with complex, predefined rules, simpower-validation checks user-defined validation rules using Regex and inserts error or success messages into your web page. Callbacks allow reacting to the overall form validation result or individual field failures.

How to use it:

1. Install and import the simpower-validation.

# NPM
$ npm i simpower-validation
// ES Module
import SimpowerValidation from 'simpower-validation';
// Browser
import SimpowerValidation from '/path/to/simpower-validation.esm.js';
// From A CDN
<script src="https://cdn.jsdelivr.net/npm/simpower-validation/simpower-validation.production.min.js"></script>

2. Create empty containers that will hold the error & success messages.

<!-- Your Form -->
<form id="form">
  <label for="name"Username:</label>
  <input id="name" name="name" type="text" placeholder="Your Username" />
  <label for="email">Email:</label>
  <input id="email" name="email" type="email" placeholder="Your email address" />
  <button type="submit">Submit The Form</button>
</form>
<!-- Messages -->
<div id="all">
  Error/Success messages for all form fields will be placed here.
</div>
<div id="email">
  Error/Success messages for the email field will be placed here.
</div>

3. Initialize the SimpowerValidation on your HTML form.

const validator = new window.SimpowerValidation('#form', {
  validateFieldOnEvent: {
    fieldValueHandler(fieldValue) {
      return fieldValue;
    },
    ruleErrorMessages: {
      on: true,
      position: {
        append: '#all',
      },
      removeContainerFromDOMAfterSuccess: true,
      // custom CSS classes for error messages
      classes: ['message', 'message-error'],
    },
    successfulValidationMessage: {
      on: true,
      successMessage: 'Validation succeeded',
      position: {
        append: '#all',
      },
      removeContainerFromDOMAfterFail: true,
      classes: ['message', 'message-success'],
    },
    invalidViewOfField: {
      on: true,
      classes: ['input-invalid'],
    },
    validViewOfField: {
      on: true,
      classes: ['input-valid'],
    },
  },
});

4. Add validation rules using Regex and JS functions. Here are some useful resources to find the perfect Regex.

validator
  // validate username
  .addField('name', [
    {
      validator(inputValue) {
        return inputValue.trim();
      },
      errorMessage: 'Usrname is required',
    },
    {
      validator(inputValue) {
        const nameRegEx = /^[a-zA-Z]{1,40}$/;
        return inputValue.match(nameRegEx);
      },
      errorMessage: 'Name is invalid',
    },
  ])
  // validate email address
  .addField(
    'email',
    [
      {
        validator(inputValue) {
          if (!inputValue.trim()) {
            return true;
          }
          const emailRegEx =
            /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
          return inputValue.match(emailRegEx);
        },
        errorMessage: 'Email is invalid',
      },
    ],
    // override options for specific form fields
    {
      event: 'input',
      ruleErrorMessages: {
        position: {
          append: '#email',
        },
      },
      successfulValidationMessage: {
        position: {
          append: '#email',
        },
      },
    }
  );
  // more rules here

5. All possible options.

validateFieldOnEvent: {
  // JavaScript event to trigger form validation
  event: null,
  // validate form fields after the first submition
  afterFirstSubmition: true,
  // disable the form fields during form validating
  lockInputOnValidation: false,
  // a function to handle field values
  fieldValueHandler: null,
  // options for error messages
  ruleErrorMessages: {
    on: true,
    position: null,
    container: null,
    removeContainerFromDOMAfterSuccess: true,
    classes: null,
  },
  // options for success messages
  successfulValidationMessage: {
    on: false,
    successMessage: null,
    position: null,
    container: null,
    removeContainerFromDOMAfterFail: true,
    classes: null,
  },
  // options for valid/invalid views of form fields
  invalidViewOfField: {
    on: false,
    classes: null,
  },
  validViewOfField: {
    on: false,
    classes: null,
  },
},
validateOnSubmit: {
  // disable the form on validate
  lockFormOnValidation: false,
  // re-validate all fields before submitting
  revalidateAllFieldsBeforeSubmition: false,
  
},

6. Event handlers.

validator.onStartValidation(callback: function, eventName: string): validation
validator.onEndValidation(callback: function, eventName: string): validation
validator.onSuccess(callback: function, eventName: string): validation
validator.onFail(callback: function, eventName: string): validation

You Might Be Interested In:


Leave a Reply