0.3.7 β€’ Published 3 years ago

formurai v0.3.7

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

Formurai

Validating forms has never been so easy. A few lines of code and your form is validated

import Formurai from 'formurai';

const rules = {'login-email': ['email']};

const errors = {
  'login-email': {WRONG_EMAIL: 'Email must be valid'}
};

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

const validator = new Formurai(form);
validator.init(rules, errors);

Table of Contents

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

OptionTypeDefault valueDescription
errorClassstring'formurai-error'The class that will be added to the field with an error
successClassstring'formurai-success'The class that will be added to the field with an success
wrapperClassstring'formurai-container'The wrapper class to which the error or success class will be added
errorMessageClassstring'formurai-message'The class of the element into which the error will be displayed must be inside the wrapperClass
withWrapperbooleantrueIf 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
autoTrimbooleantrueRemoves spaces before and after validated values
vibratebooleantrueIf an error occurs while submitting the form, a vibration is triggered. Support devices
notSubmitbooleanfalseIf you don't need to reload the page, after submitting the form, set true
multiStepbooleanfalseIf 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: 'leonardo@gmail.com'}

errors

Returns an object with error codes

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

errorList

Returns human-readable error list. For example, if you need to show all errors somewhere in one place

validator.errorList // {name: "First name required", email: "Email must be valid"}

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

formInvalid

This listener is triggered when the form is invalid, regardless of whether the click submit, or you manually invoke checkForm() method

const scrollToFirstError = () => {
  const errorEl = document.querySelector('.formurai-error');
  errorEl.scrollIntoView();
}

validator.on('formInvalid', scrollToFirstError);

changeState

This listener works only in multi-step forms and triggered when you use changeState() method

const logCurrentState = (evt) => {
  console.log(evt.detail.state) // console current step
}

validator.on('changeState', scrollToFirstError);

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

RuleExampleError
eqname: {'eq': 'Snow'}'NOT_ALLOWED_VALUE'
one_ofname: {'one_of': 'Snow', 'Tirion'}'NOT_ALLOWED_VALUE'
emaillogin: 'email''WRONG_EMAIL'
integerage: 'integer''NOT_INTEGER'
min_lengthlogin: { min_length: 2 }'TOO_SHORT'
max_lengthname: { max_length: 10 }'TOO_LONG'
length_betweencode: { length_between: 2, 10'TOO_LONG' or 'TOO_SHORT'
number_betweenage: { 'number_between': 18, 95 }'TOO_HIGH' or 'TOO_LOW' or 'NOT_NUMBER'
likeprice: { like: '^\w+?$', 'i' }'WRONG_FORMAT'

Examples

Roadmap

  • Add a getter with a list of error messages
  • Add a showError method to show errors from backend
  • Implement 'formInvalid' and 'changeState' events
  • Treeshaking
  • Integration with React
  • Π‘over the validator with e2e tests
0.3.6

3 years ago

0.3.5

3 years ago

0.3.7

3 years ago

0.3.4

3 years ago

0.3.3

3 years ago

0.2.3

3 years ago

0.2.1

3 years ago

0.2.0

3 years ago

0.1.8

3 years ago

0.1.7

3 years ago

0.1.9

3 years ago

0.2.2

3 years ago

0.1.0

3 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.4

3 years ago

0.1.3

3 years ago

0.1.6

3 years ago

0.1.5

3 years ago

0.0.11

3 years ago

0.0.10

3 years ago

0.0.9

3 years ago

0.0.8

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago