All Projects β†’ Barto-dev β†’ formurai

Barto-dev / formurai

Licence: other
Lightweight and powerfull library for declarative form validation

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to formurai

Form bloc
πŸ”₯ Dart and Flutter Package πŸ”₯ Easy Form State Management using BLoC pattern πŸ”₯ Wizard/stepper forms, asynchronous validation, dynamic and conditional fields, submission progress, serialization and more! πŸ”₯
Stars: ✭ 239 (+387.76%)
Mutual labels:  forms, form
react-formulation
Simple React form validation
Stars: ✭ 14 (-71.43%)
Mutual labels:  forms, form
Fui
Add CLI & form interface to your program. Docs: https://docs.rs/fui
Stars: ✭ 244 (+397.96%)
Mutual labels:  forms, form
Redux Form
A Higher Order Component using react-redux to keep form state in a Redux store
Stars: ✭ 12,597 (+25608.16%)
Mutual labels:  forms, form
ATGValidator
iOS validation framework with form validation support
Stars: ✭ 51 (+4.08%)
Mutual labels:  validator, form
Rich Model Forms Bundle
Provides additional data mappers that ease the use of the Symfony Form component with rich models.
Stars: ✭ 198 (+304.08%)
Mutual labels:  forms, form
svelte-multistep-form
Svelte MultiStep Form like, this component is still in beta stage
Stars: ✭ 29 (-40.82%)
Mutual labels:  forms, form
React Apollo Form
Build React forms based on GraphQL APIs.
Stars: ✭ 178 (+263.27%)
Mutual labels:  forms, form
FrontendForms
A module for ProcessWire CMS to create and validate forms on the frontend easily using the Valitron library.
Stars: ✭ 0 (-100%)
Mutual labels:  forms, form
react-apollo-form
Build React forms based on GraphQL APIs.
Stars: ✭ 195 (+297.96%)
Mutual labels:  forms, form
React Form
βš›οΈ Hooks for managing form state and validation in React
Stars: ✭ 2,270 (+4532.65%)
Mutual labels:  forms, form
final-form-arrays
Array Mutators for 🏁 Final Form
Stars: ✭ 64 (+30.61%)
Mutual labels:  forms, form
React Redux Form
Create forms easily in React with Redux.
Stars: ✭ 2,099 (+4183.67%)
Mutual labels:  forms, form
aurelia-form
Fun with forms! Form utilities to make stuff just a bit (a lot) easier.
Stars: ✭ 34 (-30.61%)
Mutual labels:  forms, form
Composable Form
Build type-safe composable forms in Elm
Stars: ✭ 179 (+265.31%)
Mutual labels:  forms, form
Final Form
🏁 Framework agnostic, high performance, subscription-based form state management
Stars: ✭ 2,787 (+5587.76%)
Mutual labels:  forms, form
Core
The Form Tools Core.
Stars: ✭ 156 (+218.37%)
Mutual labels:  forms, form
Fielder
A field-first form library for React and React Native
Stars: ✭ 160 (+226.53%)
Mutual labels:  forms, form
Vue Form Json Schema
Create forms using JSON schema. Bring your components!
Stars: ✭ 253 (+416.33%)
Mutual labels:  forms, form
ember-validity-modifier
Ember Octane addon to add custom validity (form validation) to form fields
Stars: ✭ 28 (-42.86%)
Mutual labels:  forms, form

Formurai

Logo

Formurai is a lightweight and powerfull library for declarative form validation.

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.6 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"}

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', logCurrentState);

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 showError method to show errors from backend
  • Implement 'formInvalid' and 'changeState' events
  • Treeshaking
  • Integration with React
  • Π‘over the validator with e2e tests
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].