Marcisbee / radi

🌀Tiny (in size) front-end framework with no extra browser re-flows
https://radi.js.org
MIT License
948 stars 34 forks source link

Adds form validation controls #34

Closed Marcisbee closed 6 years ago

Marcisbee commented 6 years ago

Added

Usage

import { Validator } from 'radi';

<form
  action="#"
  prevent
  onsubmit={ (e, values) => (this.sendMessage(e, values)) }
  onvalidate={ e => ({
    email: value => new Validator(value)
      .required().error('E-mail is required')
      .email().error('E-mail is invalid')
      .check(),
  }) }
  error="contact-form">

  <errors
    name="contact-form"
    onrender={errors => (
      <ul class={['alert', 'alert-error']}>
        {errors.map( error => (
          <li>{ error.reason }</li>
        ))}
      </ul>
    )}
  />

  <input
    loadfocus
    placeholder="E-mail"
    name="email"
    type="email"
    validate/>

  <button
    type="submit"
    disabled
    validate-submit>
    Send message
  </button>

</form>

Usage of Validator

This radi version introduces new class Validator. It takes in value, chains validations/error messages.

At the end call .check() to validate this chain and it returns true or "Error message".

After every validation rule we can call .error(String). It will serve as error message if validation rule before this fails.

Default validation rules

new Validator("name@name")
   .required().error('E-mail is required')
   .email().error('E-mail is invalid')
   .check()

This will return "E-mail is invalid"