Lightweight and powerfull library for declarative form validation

Overview
Logo

Formurai is a lightweight and powerfull library for declarative form validation

Features

  • πŸ“¦ Just 4.4 KB gzipped
  • πŸ‘©πŸ»β€πŸ’» Rules are declarative
  • ✨ Any number of rules for each field
  • ❌ Flexible error handling and their display
  • πŸ—œ Has possibility to validate multi-step forms
  • βš™οΈ Configurable check queue
  • πŸ“œ Easy to create and reuse your own rules
  • ⚑️ Based on LIVR(Language Independent Validation Rules)
  • πŸ‘ Don't need Jquery.

Setup

Install the package

npm install formurai
yarn add formurai

JS

import Formurai from 'formurai';

// define rules
const rules = {
  'login-email': ['required', 'email'],
};

// define errors for user, its optional
const errors = {
  'login-email': {
    REQUIRED: 'Email required',
    WRONG_EMAIL: 'Email must be valid',
  }
};

const form = document.querySelector('#login');
const validator = new Formurai(form);
validator.init(rules, errors);

ALL RULES AND ERROR CODES

As a key for the rules, you need to pass the name of the field to be validated. The field name must be unique within this form

HTML

<form id="login">
  
  <section class="formurai-container">
    <input name="login-email" type="email">
    <span class="formurai-message"></span>
  </section>

  <button type="submit">Submit</button>
  
</form>

If you need to show errors in the interface, add the formurai-container class to the element to which you want to assign the error or success class (optional step).

To display an error, inside the container, define an element with the class formurai-message, errors that you pass during initialization will be displayed here (optional step).

CSS

.formurai-message {
  display: none;
}

.formurai-error .formurai-message {
  display: none;
}

.formurai-error input {
  border: 1px solid red;
}

.formurai-success input {
  border: 1px solid green;
}

When the form is submitted, or the checkForm method is called, the wrapper(.formurai-container) is assigned an error or success class.

Usage

Basic usage, you need to pass the form and rules.

/**
 * @param {HTMLFormElement} form 
 * @param {Object} options 
 * @type {Formurai}
 */
const validator = new Formurai(form, options);
validator.init(rules);

Options

Option Type Default value Description
errorClass string 'formurai-error' The class that will be added to the field with an error
successClass string 'formurai-success' The class that will be added to the field with an success
wrapperClass string 'formurai-container' The wrapper class to which the error or success class will be added
errorMessageClass string 'formurai-message' The class of the element into which the error will be displayed must be inside the wrapperClass
withWrapper boolean true If you do not need to show error messages and it will be enough for you to add an error or success class to the field, set false
autoTrim boolean true Removes spaces before and after validated values
vibrate boolean true If an error occurs while submitting the form, a vibration is triggered. Support devices
notSubmit boolean false If you don't need to reload the page, after submitting the form, set true
multiStep boolean false If you need to validate a form with many steps, and each step needs to be validated separately. See multi-step example

Methods

const validator = new Formurai(form);

init(rules, messages?, initialState?)

Initializes validator, error object and initialState, optional parameters, initialState work only in multi-step forms.

validator.init(rules)

destroy()

Destroys the validator and all associated event listeners (custom to). Also delete all added rules.

validator.destroy()

changeState(state)

Change current state in multi step form. The value must be a key with the rules for the current step

const rules = {
  'step-1': {...stepRules},
  'step-2': {...stepRules},
}

validator.changeState('step-2')

checkForm()

Manually run a form validation like

const nextStepButton = document.querySelector('.next-step');

nextStepButton.addEventListener('click', () => {
  validator.checkForm();
  
  if (validator.isFormValid) {
    // go to the next step
  }
})

addRule(rule)

Accepts object or array of objects with custom rules. Rules need to be added after initialization

const rules = {
  password: 'strong_password'
}

const customRule = {
  name: 'strong_password',
  rules: [{length_between: [15, 20]}],
  error: 'WEAK_PASSWORD'
}

validator.init(rules)
validator.addRule(customRule)

formData

Returns an object with data from the form

validator.formData // {name: 'Leonardo', email: '[email protected]'}

errors

Returns an object with error codes

validator.errors // {name: "REQUIRED", email: "WRONG_EMAIL"}

isFormValid

Returns the current state of form validation

validator.isFormValid // true | false

Events

validator.on(evt, callback);

formValid

This listener is triggered when the form is fully valid, useful if you need to send it in ajax, without reloading the page.

const sendForm = async () => {
  await fetch('https://example.com', {
    method: 'POST',
    body: validator.formData // contain all form data
  })
  console.log('Your form has been submitted successfully')
}

validator.on('formValid', sendForm);

See full example

Rules

ALL RULES

All rules are based on LIVR (Language Independent Validation Rules). So all the rules that you find here you can use in this validator

Most common rules

Rule Example Error
eq name: {'eq': 'Snow'} 'NOT_ALLOWED_VALUE'
one_of name: {'one_of': ['Snow', 'Tirion']} 'NOT_ALLOWED_VALUE'
email login: 'email' 'WRONG_EMAIL'
integer age: 'integer' 'NOT_INTEGER'
min_length login: { min_length: 2 } 'TOO_SHORT'
max_length name: { max_length: 10 } 'TOO_LONG'
length_between code: { length_between: [2, 10] 'TOO_LONG' or 'TOO_SHORT'
number_between age: { 'number_between': [18, 95] } 'TOO_HIGH' or 'TOO_LOW' or 'NOT_NUMBER'
like price: { like: ['^\w+?$', 'i'] } 'WRONG_FORMAT'

Examples

Roadmap

  • Add a getter with a list of error messages
  • Add a scroll method to error input
  • Add a showError method to show errors from backend
  • Implement 'formInvalid' and 'changeState' events
  • Π‘over the code with tests
You might also like...

jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

Jan 3, 2023

The most powerful data validation library for JS

joi The most powerful schema description language and data validator for JavaScript. Installation npm install joi Visit the joi.dev Developer Portal f

Jan 4, 2023

A simple credit cards validation library in JavaScript

creditcard.js A simple credit cards validation library in JavaScript. Project website: https://contaazul.github.io/creditcard.js Install creditcard.js

Jan 7, 2023

v8n β˜‘οΈ ultimate JavaScript validation library

v8n β˜‘οΈ ultimate JavaScript validation library

The ultimate JavaScript validation library you've ever needed. Dead simple fluent API. Customizable. Reusable. Installation - Documentation - API Intr

Dec 30, 2022

Schema-Inspector is an JSON API sanitisation and validation module.

Schema-Inspector is an JSON API sanitisation and validation module.

Schema-Inspector is a powerful tool to sanitize and validate JS objects. It's designed to work both client-side and server-side and to be scalable wit

Oct 3, 2022

:white_check_mark: Easy property validation for JavaScript, Node and Express.

property-validator βœ… Easy property validation for JavaScript, Node and Express Built on top of validator.js, property-validator makes validating reque

Dec 14, 2022

TypeScript-first schema validation for h3 and Nuxt applications

h3-zod Validate h3 and Nuxt 3 requests using zod schema's. Install npm install h3-zod Usage import { createServer } from 'http' import { createApp } f

Dec 28, 2022

Simple, smart and pleasant validation solution.

nice-validator Simple, smart and pleasant validation solution. Download the latest release or install package via npm or bower $ npm install nice-vali

Nov 18, 2022

String validation

validator.js A library of string validators and sanitizers. Strings only This library validates and sanitizes strings only. If you're not sure if your

Jan 5, 2023
Owner
Illia
Illia
Lightweight JavaScript form validation library inspired by CodeIgniter.

validate.js validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter. Features Validate form fields from over a dozen r

Rick Harrison 2.6k Dec 15, 2022
FieldVal - multipurpose validation library. Supports both sync and async validation.

FieldVal-JS The FieldVal-JS library allows you to easily validate data and provide readable and structured error reports. Documentation and Examples D

null 137 Sep 24, 2022
Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

upjs 314 Dec 26, 2022
Cross Browser HTML5 Form Validation.

Validatr Cross Browser HTML5 Form Validation. Getting Started View the documentation to learn how to use Validatr. Changelog Version 0.5.1 - 2013-03-1

Jay Morrow 279 Nov 1, 2022
jQuery form validation plugin

jQuery.validationEngine v3.1.0 Looking for official contributors This project has now been going on for more than 7 years, right now I only maintain t

Cedric Dugas 2.6k Dec 23, 2022
HTML 5 & Bootstrap Jquery Form Validation Plugin

HTML 5 & Bootstrap Jquery Form Validation Plugin HTML 5 & Bootstrap 5 & Jquery 3 jbvalidator is a fresh new jQuery based form validation plugin that i

null 37 Dec 6, 2022
A lightweight NodeJS library for strict mime-type validation on streams

A lightweight NodeJS library for strict mime-type validation on streams. It gets a ReadableStream and decets the mime-type using its Magic number and validates it using the provided allowed and forbidden lists; If it's allowed it will pass it to the created WritableStreams and if it's not it will throw an error.

CEO of Death Star 9 Apr 3, 2022
This Login Form made using React hooks , React Js , Css, Json. This form have 3 inputs, it also validate those inputs & it also having length limitations.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Yogesh Sharma 0 Jan 3, 2022
Themis is a validation and processing library that helps you always make sure your data is correct.

Dataffy Themis - The advanced validation library Themis is a validation and processing library that helps you always make sure your data is correct. Β·

Dataffy 14 Oct 27, 2022
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023