use-form-validator
Hook for form validation in React
Installation
npm add use-form-validator
Usage
API
import React useState useCallback from "rect";import useFormValidator from "use-form-validator"; { // data is an object of form field values, .e.g {name: "Bob", email: "bob@example.com"} const data setData = ; const rules = ; // Default message overrides const messages = ; const validator = ; // validator.valid => boolean if form validation state // validator.errors.all => array of form errors // validator.errors.get(name) => array of errors for field // validator.errors.first(name) => first error for field or null if there is no error}
Basic Example
import React useState useCallback from "rect";import useFormValidator from "use-form-validator"; { const data setData = ; const rules = ; // Default message overrides const messages = ; const validator = ; const onSubmit = ; const onChange = ; return <form => <div> /* "name" error message */ <input ="name" = /> validatorerrors </div> <div> <input ="email" = /> /* "email" error message */ validatorerrors </div> <div> <button>submit</button> </div> </form> ;}
Available Rules
Rule | Description |
---|---|
required | Test value has a value |
min:min | Test value length or number is >= min |
max:max | Test value length or number is <= max |
Test value email format | |
between:min,max | Test value length or number between min and max |
Contributing
All contributions are welcome, just submit a PR with a clear explanation of your changes.
Changes to the lib are made inside src/lib
and changes to examples are made inside src/examples
Running Examples
The following commands will serve the examples on localhost:8081.
npm installnpm run watch-examples
Making a Release
The below script will bump the major, minor, or patch number by one and make a new NPM and Github release.
npm run release {release: ["major", "minor", "patch"]} # e.g. npm run release patch