Skip to content

Vanilla validation for your existing forms, while making all kinds of customizations to fit your application really easy.

License

Notifications You must be signed in to change notification settings

mitera/vanilla-form-validator

Repository files navigation

vanilla-form-validator.js

License: MIT TypeScript Socket Badge jsdelivr npm npm downloads yarn

Inspired by: jquery-validation

Form Validator: provides validation for your existing forms, while making all kinds of customizations to fit your application really easy.

Demo - Features - Install - Usage - Options - Changelog - License

Demo

See the vanilla-form-validator.js demo.

Best practice

Use this library to validate a form and display the same style for error messages.

Features

  • validate a form
  • validate fields
  • preconfigured and internationalizable error messages
  • customize the submission form
  • create a custom validations
  • tested in Edge, Chrome, Firefox

Install

CDN via jsDelivr

<script src="https://cdn.jsdelivr.net/npm/vanilla-form-validator@latest/dist/vanilla-form-validator.min.js" type="text/javascript"></script>

Download vanilla-form-validator.js and include the script in your HTML file:

<script src="vanilla-form-validator.js" type="text/javascript"></script>

You can also install using the package managers NPM.

npm install vanilla-form-validator

modular code

import 'vanilla-form-validator'

Usage

let commentForm = new FormValidator("#commentForm");

let commentForm = new FormValidator("#commentForm", {
    errorElement: 'label',
    errorClass: 'error',
    ignore: 'input[type="hidden"]'
});

Where options is an optional parameter.
See below for a description of the available options and defaults.

Options

The default options are:

{
    ignore: null,
    rules: null,
    errorElement: 'p',
    errorClass: 'error',
    errorFieldClass: null,
    validFormClass: 'was-validated',
    submitHandler: null,
    messages: this.messages
}

Where:

  • ignore is an optional string containing one or more selectors to match fields to ignore. This string must be a valid CSS selector string
  • rules is an array of custom fields validation Custom validations
  • errorElement is an html tag to display error message
  • errorClass is a css class for display error message
  • errorFieldClass is a css class added when a field is not valid
  • validFormClass is a css class added to a form when form is valid
  • submitHandler is an method to customize the submission form Customize the submission form
  • messages preconfigured error messages Error messages

Error messages

Preconfigured values are:

private messages: FormMessages = {
    required: 'This field is required.',
    remote: 'Please fix this field.',
    email: 'Please enter a valid email address.',
    url: 'Please enter a valid URL.',
    date: 'Please enter a valid date.',
    number: 'Please enter a valid number.',
    phone: 'Please enter a valid phone.',
    file: 'Please select a file.',
    equalTo: 'Please enter the same value again.',
    maxlength: 'Please enter no more than {0} characters.',
    minlength: 'Please enter at least {0} characters.',
    rangelength: 'Please enter a value between {0} and {1} characters long',
    max: 'Please enter a value than {0}.',
    min: 'Please enter a value at least {0}.',
    range: 'Please enter a value between {0} and {1}'
}

Override solution:

  1. one by one, below an example:

     let messages = {
         required: 'Required field' //override default message
     }
     let signupForm = new FormValidator("#signupForm", {
         errorElement: 'label',
         messages: messages,
     });
    
  2. loading a json file commentForm.loadMessages('localization/messages_es.json');

    let commentForm = new FormValidator("#commentForm", {
        errorElement: 'label',
        ignore: 'input[type="hidden"]'
    });
    commentForm.loadMessages('localization/messages_es.json');
    

    On package are present a preconfigured set of json files

  3. Set on field the attribute data-error-message

    <p>
        <label for="ccomment">Your comment (required)</label>
        <textarea id="ccomment" name="comment" required data-error-message="Custom error message"></textarea>
    </p>
    

Customize the position of error message

By default, the error message will be created after the field; if you want to put the error message in another location, simply create a html tag with id the field id or name if input type is radio or checkbox, append the -error suffix (ex: id="cemail-error") and hide style="display: none;"

<p>
    <label for="cemail">E-Mail (required)</label>
    <input id="cemail" type="email" name="email" required />
</p>
<label id="cemail-error" class="error" style="display: none;"></label>

Customize the submission form

Create a function on submitHandler property

let signupForm = new FormValidator("#signupForm", {
    submitHandler: function () {
        console.log('remote action')
    }
});

Custom validations

is an array of rules:

let signupForm = new FormValidator("#signupForm", {
    rules: [
        ...
    ]
})

rules configuration:

  • fieldName is the name of the field
  • errorMessage is an optional error message
  • validation is an object to configure
    • method available methods are: equalTo, minlength, maxlength, rangelength, custom
    • field is a css rule for find a field, this option is use by equalTo method
    • min is min integer value used by minlength, rangelength
    • max is max integer value used by maxlength, rangelength
    • action is a custom method for validate field must be return a boolean value

Preconfigured validation are: equalTo, minlength, maxlength, rangelength

These rules: minlength, maxlength, rangelength are applicable on input text,radio,checkbox,file and select field

Example of preconfigured validation:

{
    fieldName: 'confirm_password',
    validation: {
        method: 'equalTo',
        field: '#password'
    }
},
{
    fieldName: 'minselect',
    errorMessage: 'Please select 2 elements.',
    validation: {
        method: 'minlength',
        min: 2
    }
},
{
    fieldName: 'maxfiles',
    errorMessage: 'Please select max 2 files.',
    validation: {
        method: 'maxlength',
        max: 2
    }
},
{
    fieldName: 'topic2',
    errorMessage: 'Please select 1 or 2 topics',
    validation: {
        method: 'rangelength',
        min: 1,
        max: 2
    }
}

Example of custom validation:

{
    fieldName: 'username',
    errorMessage: 'Username already in use',
    validation: {
        method: 'custom',
        action: function () {
            console.log('remote validation');
            return true;
        },
    }
}

Changelog

To see what's new or changed in the latest version, see the changelog

License

vanilla-form-validator.js is licensed under The MIT License (MIT)
Copyright (c) 2025 Simone Miterangelis

This license is also supplied with the release and source code.
As stated in the license, absolutely no warranty is provided.

About

Vanilla validation for your existing forms, while making all kinds of customizations to fit your application really easy.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published