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";
function Form() {
const [data, setData] = useState({});
const [rules] = useState({
name: "required|max:255",
email: "required|max:255|email",
});
const [messages] = useState({
required: "This field is required",
name: {
required: "Please enter your name",
},
});
const validator = useFormValidator(data, rules, messages);
}
Basic Example
import React, { useState, useCallback } from "rect";
import useFormValidator from "use-form-validator";
function Form() {
const [data, setData] = useState({});
const [rules] = useState({
name: "required|max:255",
email: "required|max:255|email",
});
const [messages] = useState({
required: "This field is required",
name: {
required: "Please enter your name",
},
});
const validator = useFormValidator(data, rules, messages);
const onSubmit = useCallback(
(event) => {
event.preventDefault();
if (validator.valid) {
console.log(data);
}
},
[validator]
);
const onChange = useCallback(
({ target: { name, value } }) => {
setData((data) => {
data[name] = value;
return data;
});
},
[setData]
);
return (
<form onSubmit={onSubmit}>
<div>
{/* "name" error message */}
<input name="name" onChange={onChange} />
{validator.errors.first("name")}
</div>
<div>
<input name="email" onChange={onChange} />
{/* "email" error message */}
{validator.errors.first("email")}
</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 |
email | 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 install
npm 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"]}