Git Product home page Git Product logo

react-vld's Introduction

react-vld / preact-vld

npm

Simple and flexible validation for React and Preact components.

  • The main thing here is Validator component. Use it as a wrapper for your input components, forms, or whatever component you want to validate.

  • Validator accepts children prop as a function and passes the validation state as a parameter into it.

  • For updating validation state Validator uses a functional prop - rule. If a ValidationError was thrown within the rule, then validation fails, and the Validator updates validation state.

  • By default, Validator is rerendered every time the validation state is updated.

  • You can nest Validator components. The parent Validator fails when any of the child Validator fails.

Installation

For React

npm i react-vld

For Preact

npm i preact-vld

Usage

Example of Input component

import { Validator, ValidationError } from 'react-vld' // or from 'preact-vld'

export default () => {
  const [value, setValue] = useState('')

  const checkValue = useCallback(() => {
    if (value.trim() === '') {
      throw new ValidationError('Required field')
    }
  }, [value])

  const handleChange = useCallback((ev) => {
    setValue(ev.target.value)
  }, [])
  
  return (
    <Validator rule={checkValue}>
      { ({ validate, isInvalid, validationError }) => (
        <Fragment>
          <input 
            value={value}
            onBlur={validate}
            onChange={handleChange}
          />
          { isInvalid && (
            <div>
              { validationError.message }
            </div>
          ) }
        </Fragment>
      ) }
    </Validator>
  )
}

Example of Form component (nesting)

import { Validator, ValidationError } from 'react-vld' // or from 'preact-vld'

export default () => (
  <Validator>
    { ({ validate }) => {
      const handleSubmit = useCallback((ev) => {
        ev.preventDefault()

        if (validate().isValid) {
          alert('Submitted!')
        }
      }, [validate])

      return (
        <form onSubmit={handleSubmit}>
          <Input />
          <button type="submit" />
        </form>
      )
    } }
  </Validator>
)

API

Validator props

  • rule() used to calculate new validation state

  • mapError(validationError) transforms validation error, may be useful for adding some payload to the error

  • children(validationState)

validationState has the following structure

  • validate({ updateComponent = true } = {}) invokes validation routine (calling rule and also calling validate for every child Validator)

  • resetValidation({ updateComponent = true } = {}) resets validation state (also calling resetValidation for every child Validator)

  • isValid = true|false|undefined

  • isInvalid = true|false|undefined

  • validationError = ValidationError|undefined

ValidationError

  • constructor(message, payload)

License

MIT

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.