Custom HTML5 Form Validator In Vanilla JavaScript – Just-validate

Category: Form , Javascript | May 18, 2022
Author:horprogs
Views Total:2,189 views
Official Page:Go to website
Last Update:May 18, 2022
License:MIT

Preview:

Custom HTML5 Form Validator In Vanilla JavaScript – Just-validate

Description:

Just-validate is a dependency-free, HTML5 data attribute-based form validation that supports both client-side and server-side form validation.

Validation rules are fully customizable via JavaScript. Compatible with Bootstrap framework.

Install it via package managers.

# NPM
$ npm install just-validate
# Bower
$ bower install just-validate

Basic usage:

1. Import the Just-validate library or directly load the minified version of the Just-validate library in the html document.

import JustValidate from 'just-validate';
<script src="/dist/just-validate.production.min.js"></script>

2. Define your validation rules and apply them to form fields. All available rules:

  • required
  • email
  • minLength
  • maxLength
  • number
  • minNumber
  • maxNumber
  • password
  • strongPassword
  • customRegexp
  • minFilesCount
  • maxFilesCount
  • files
// initialize the validation library
const validation = new JustValidate('#form', {
      errorFieldCssClass: 'is-invalid',
});
// apply rules to form fields
validation
  .addField('#name', [
    {
      rule: 'minLength',
      value: 3,
    },
    {
      rule: 'maxLength',
      value: 30,
    },
  ])
  .addField('#email', [
    {
      rule: 'required',
      errorMessage: 'Field is required',
    },
    {
      rule: 'email',
      errorMessage: 'Email is invalid!',
    },
  ])
  .addField('#password', [
    {
      rule: 'password',
    },
  ])
  .addField('#message', [
    {
      validator: (value) => {
        return value[0] === '!';
      },
    },
  ])
  .addField('#consent_checkbox', [
    {
      rule: 'required',
    },
  ])
  .addField('#favorite_animal_select', [
    {
      rule: 'required',
    },
  ])
  .addRequiredGroup(
    '#read_terms_checkbox_group',
    'You should select at least one communication channel'
  )
  .addRequiredGroup('#communication_radio_group')
  .onSuccess((event) => {
    console.log('Validation passes and form submitted', event);
  });

3. More API methods.

validation
  // on fail event
  .onFail(fields) => { // ...})
  // re-validate fileds
  .revalidateField(field: string).then(isValid => {})
  // revalidate the form
  .revalidate().then(isValid => {})
  // remove validation rules/events/errors from a field
  .removeField(field: string)
  // remove validation rules/events/errors from a group
  .removeGroup(group: string)
  // show errors programmatically
  .showErrors({ '#email': 'The email is invalid' })
  // show success labels
  .showSuccessLabels({
    '#email': 'The email looks good!',
  });
  // refresh the form
  .refresh()
  // destroy the instance
  .destroy()

4. Customize the form validation library.

const validation = new JustValidate('#form', {
      errorFieldCssClass: 'is-invalid',
      errorFieldStyle: {
        border: '1px solid red',
      },
      errorLabelCssClass: 'is-label-invalid',
      errorLabelStyle: {
        color: 'red',
        textDecoration: 'underlined',
      },
      successFieldCssClass: 'just-validate-success-field',
      successLabelCssClass: 'just-validate-success-label',
      focusInvalidField: true,
      lockForm: true,
      successMessage: 'Success Message',
      tooltip: {
        position: 'top',
      },
      },
      [  // localize the library here
        {
          key: 'Name is too short',
          dict: {
            ru: 'Имя слишком короткое',
            es: 'El nombre es muy corto',
          },
        },
        {
          key: 'Field is required',
          dict: {
            ru: 'Обязательное поле',
            es: 'Se requiere campo',
          },
        },
      ]
});

Changelog:

v3.8.1 (05/18/2022)

  • Bug Fixes

v3.8.0 (05/18/2022)

  • add showSuccessLabels method

v3.7.0 (05/05/2022)

  • made it possible to define multiple class names as a string and list of strings

v3.6.1 (05/03/2022)

  • fix reset disabled attr unlockForm

v3.6.0 (05/02/2022)

  • add showErrors method

v3.5.2 (04/19/2022)

  • Bug Fixes

v3.5.1 (02/19/2022)

  • return the validation result in revalidate methods

v3.5.0 (02/15/2022)

  • add revalidate() and revalidateField() methods for manual revalidation

v3.4.0 (02/01/2022)

  • add custom error labels placement

v3.3.4 (01/28/2022)

  • add field method

v3.3.3 (01/27/2022)

  • Bug Fixes

v3.3.2 (01/26/2022)

  • Bug Fixes

v3.3.1 (01/19/2022)

  • Bug Fixes

v3.3.0 (01/10/2022)

  • add conditional messages
  • add success messages

v3.2.0 (12/30/2021)

  • add date validation and plugin support

v3.1.2 (12/30/2021)

  • Bugfixes

v3.1.1 (12/27/2021)

  • Bugfixes

v3.1.0 (12/27/2021)

  • add minFilesCount, maxFilesCount, files rules for files validation

v3.0.0 (12/27/2021)

  • rules for maxLength, maxNumber etc. will not raise an error if the field is empty and there is no required rule. To validate for required you should define required rule directly.
  • change required logic

v2.2.0/1 (12/27/2021)

  • change required logic

v2.1.0 (12/22/2021)

  • add removeField method

v2.0.0 (12/07/2021)

  • add basic methods, ecosystem, basic test
  • add group validation, rename interfaces, render errors
  • add localisation, fix select
  • add new tooltips
  • add onFail callback
  • add rendering, clearing errors
  • bugfixes

09/28/2019

  • v1.5.0: Added focusWrongField and invalidFormCallback

06/29/2019

  • v1.4.0: Added feature to allow the user to provide their own validation function

04/13/2019

  • v1.3.1: fix(semver): test semver

12/02/2018

  • v1.3.0: Added feature for check required radio buttons

09/22/2018

  • v1.2.0: fix path, rename params

You Might Be Interested In:


One thought on “Custom HTML5 Form Validator In Vanilla JavaScript – Just-validate

Leave a Reply