https://github.com/bestguy/react-use-validated-input
React Hook for validating input values
https://github.com/bestguy/react-use-validated-input
Last synced: 4 months ago
JSON representation
React Hook for validating input values
- Host: GitHub
- URL: https://github.com/bestguy/react-use-validated-input
- Owner: bestguy
- Created: 2019-12-12T05:38:17.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2025-06-24T06:39:30.000Z (12 months ago)
- Last Synced: 2025-10-23T02:57:35.069Z (8 months ago)
- Language: JavaScript
- Homepage: https://bestguy.github.io/react-use-validated-input/
- Size: 1.59 MB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# react-use-validated-input
React hook for using input state with validation.
Optionally exposes a [validate.js](https://validatejs.org/) helper.
----
## Syntax
```javascript
const [state, { onBlur, onChange, value }, validationMessage, isValid] =
useValidatedInput(initialState, getValidationMessage, validateImmediately, validateOnChange]);
```
Returns a state value, an object you can spread to an input, a validation message (if invalid), and whether it's valid.
### Parameters
`initialState`
The initial state value. During the initial render, the returned state is the same as this value.
`getValidationMessage`
Function that receives the current state value, and should return a validation string if invalid, otherwise should return `undefined`;
`validateImmediately`
Optional. Boolean value whether to validate on initial render, otherwise will validate after first blur.
Default value:
`false`
`validateOnChange`
Optional. Boolean value whether to validate on change (and before blur), otherwise will validate after first blur.
Default value:
`false`
### Return value
The return value is an array with the following values:
`state`
The current state value.
`inputProps`
An object with the following properties:
- `onBlur`
- `onChange`
- `value`
This can be spread onto an input to automatically manage state updates and validation.
`validationMessage`
A string describing the validation failures, if any.
`isValid`
A boolean value indicating if the state passes the validation.
Returns undefined if validation has not been been run.
### Usage
```javascript
const regex = /[^@]+@[^\.]+\..+/;
const isEmail = value => !value.match(regex) && 'Please type a valid email address';
const isRequired = value => value.length === 0 && 'This field is required';
const [username, usernameProps, usernameFeedback, usernameInvalid] =
useValidatedInput('', isEmail);
const [pwd, pwdProps, pwdFeedback, pwdInvalid] = useValidatedInput(password, isRequired);
return (
alert(username, pwd)}
>
Username
{usernameFeedback}
Password
{pwdFeedback}
);
```