https://github.com/bestguy/react-use-validated-state
React hook for using state with validation
https://github.com/bestguy/react-use-validated-state
Last synced: 5 months ago
JSON representation
React hook for using state with validation
- Host: GitHub
- URL: https://github.com/bestguy/react-use-validated-state
- Owner: bestguy
- Created: 2018-12-28T07:13:33.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T21:38:24.000Z (over 3 years ago)
- Last Synced: 2025-03-18T13:26:26.616Z (over 1 year ago)
- Language: JavaScript
- Size: 405 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 22
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# react-use-validated-state
React hook for using state with validation. Uses [validate.js](https://validatejs.org/)
----
## Syntax
```javascript
const [state, setState, isValid, validationMessage, validate] =
useValidatedState(initialState, getValidationMessage, validateImmediately]);
```
Returns a stateful value, a function to update it, whether it's valid, and validation message (if invalid).
### Parameters
`initialState`
The initial state value. During the initial render, the returned state is the same as this value.
`getValidationMessage`
Optional. Function that receives the current state value, and returns a validation string if invalid, otherwise should return `undefined`;
Default value:
`() => undefined`
`validateImmediately`
Optional. Boolean value whether to validate on initial render, otherwise will validate after first change.
Default value:
`false`
### Return values
`state`
The current state value.
`setState`
Function used to update the state. It accepts a new state value and enqueues a re-render of the component.
`isValid`
A boolean value indicating if the state passes the validationConstraints.
Returns undefined if validation has not been been run.
`validationMessage`
Optional. A string describing the validation failures, if any.
`validate`
Optional. Function used to trigger validation, even if state is unchanged.
Useful for validating an unchanged value on blur.
### Usage
```javascript
const [username, setUsername, usernameValid, usernameValidationMessage, validateUsername] =
useValidatedState('', { presence: true, email: true });
const [pwd, setPwd, pwdValid, validatePwd] =
useValidatedState(password, { presence: true, length: { minimum: 6 } });
return (
Username
setUsername(e.target.value)}
onBlur={() => validateUsername()}
/>
{usernameMessage}
Password
setPwd(e.target.value)}
onBlur={() => validatePwd()}
/>
{pwdMessage}
);
```