Simple-as-possible React form validation
JavaScript HTML
Latest commit 24f4cc4 Sep 15, 2017 @zackify zackify Better value checking

README.md

React Validify

CircleCI Coverage Status

Why

Validating form inputs in React is one of two things. A manual process that you build into every app, or something you get from pulling in a huge library. This package aims to provide form validation with the smallest amount of code change to your apps! Make a small field wrapper that receives input props and handles error messages, set some rules, and that's it!

Install

npm install react-validify
import Form from 'react-validify'

<Form
  rules={{
    email: 'email|required',
    password: 'required|min:8'
  }}
>
  <Input name="email" />
  <Input name="password" type="password" />

  <div
    submit
    onClick={values =>
      console.log(
        'this will be called if validation passes',
        values
      )
    }
  >
    Submit!
  </div>
</Form>

Usage

This component is the simplest way to validate form inputs in React. There's two things to learn. The Form accepts a prop called rules. This is an object with the names of all yours inputs and the rules for them. Rules can be found here. Place the submit prop on any element that you want to trigger the validation. The onClick will not be triggered until the rules pass. If validation fails, error messages will be passed to the inputs as an error prop.

Workflow:

  1. Import Form
  2. Build a wrapper around inputs. It needs to handle when there's an error passed in:
export default ({ error, ...props }) => {
  return (
    <div>
      <p>{error}</p>
      <input {...props} />
    </div>
  );
};
  1. Add a submit button inside the form with the submit prop.
  2. That's it!

Props

rules

You can see a list of rules here

errorMessages

Custom error messages. You can see how these work here

errorMessages={{
  'required.email': 'Custom error message',
  'min.password': 'Custom min password required error message.'
}}

onValues

exposes the values on change, you must manage the form state by passing in values if using this. Ex: values={this.state.values} must be passed too, if using the example below)

onValues={values => this.setState({ values })}

values

Set values when the form is first rendered.

values={{name: 'set'}}

onEnter

Triggers a submit when enter is pressed on an input

<Input name="email"  onEnter={this.submit}/>

attributeNames

Custom attribute names. You can see how these work here. Currently does not support validatorjs's attributeFormatter.

attributeNames={{
  email: 'Email address'
}}

errors

Set errors manually, in case the server comes back with messages.

errors={{name: 'Email is invalid...'}}

Contributors

Thanks goes to these wonderful people (emoji key):


Zach Silveira


Ryan Castner

This project follows the all-contributors specification. Contributions of any kind welcome!