π£
form-validation-hooks
React hooks to help validate forms
Β
Validate individual inputs.
import React from 'react';
// π Import form-validation-hooks.
import { useValidations, useTouched } from 'form-validation-hooks';
const Input = ({ name, value, type, form, validations, handleChange }) => {
// π Validate inputs.
const errors = useValidations({ name, value, form, validations });
// π Get touched state.
const touched = useTouched(value);
// πConditionally render errors based on touched state.
return (
<>
<input name={name} value={value} onChange={handleChange} type={type} />
<p>
<small style={{ color: 'red' }}>{touched && errors.join(' ')}</small>
</p>
</>
)
}
Validate the entire state of a form.
import React, { useState } from 'react';
import Input from './Input';
// π Import form-validation-hooks.
import { useForm } from 'form-validation-hooks';
// π Import custom validations.
import validations from './validations';
const SignupForm = () => {
const [user, setUser] = useState({
email: '',
password: '',
confirmPassword: '',
test: '',
});
// π Validate the entire form.
const form = useForm({ validations, form: user })
const handleChange = (event) => {
const { target, target: { name } } = event;
const value = target.type === 'checkbox' ? target.checked : target.value;
setUser({ ...user, [name]: value });
}
// π Disable submit button if form is invalid.
return (
<>
<label>Email:</label>
<Input
name="email"
type="text"
value={user.email}
validations={validations}
form={user}
handleChange={handleChange}
/>
<label>Password:</label>
<Input
name="password"
type="password"
value={user.password}
validations={validations}
form={user}
handleChange={handleChange}
/>
<label>Confirm Password:</label>
<Input
name="confirmPassword"
type="password"
value={user.confirmPassword}
validations={validations}
form={user}
handleChange={handleChange}
/>
<button disabled={!form.isValid}>Signup</button>
</>
);
};
Write your own validations.
const validEmail = (value) => {
if (/@/.test(value)) return;
return 'Invalid email address.';
};
const length = ({ min = 2, max = 10 }) => (value) => {
if (value.length < min) return `Must be at least ${min} characters.`;
if (value.length > max) return `Must be less than ${max} characters.`;
return;
};
const matchingValues = ({ name, label = name } = {}) => (value, form) => {
if (value === form[name]) return;
return `Does not match ${label}.`;
};
const validations = {
email: [validEmail],
password: [length({ min: 6, max: 24 })],
confirmPassword: [matchingValues({ name: 'password' })],
};
Β
Introduction
npm install form-validation-hooks
form-hook-validations
is a set of hooks that can validate the entire state of a form, or just an input.
You bring in your own validations.
Features
- Validate individual input fields.
- Validate the entire form.
- Validations based on sibling input fields.
- Custom validations.
- Keep validations outside of your component.
- Keep track of touched/dirty state.
Β
API Reference
useValidations({ name, value, validations, form })
Arguments
-
options
(object):-
name
(string): The key/name of the input being validated. -
value
(any): The value of the input. -
validations
(object): An object that specifies validations for each input. -
form
(object): Optional, the form object which holds all of the form data.
-
Returns
(array): An array containing all of the validations error for the input, the array will be empty if there are no validation errors.
['Invalid email address.']
Example
const errors = useValidations({ name, value, form, validations });
useForm({ validations, form })
Arguments
-
options
(object):-
validations
(object): An object that specifies validations for each input. -
form
(object): Optional, the form object which holds all of the form data.
-
Returns
(object): An objecting containg all form errors and valid state.
{
isValid: true, // true or false
errors: {
// There will be a key for inputs with specified validations.
// An array containing all of the validations error for the input, the array will be empty if there are no validation errors.
email: [],
confirmPassword: []
}
}
Example
const form = useForm({ validations, form: user })
useTouched(value)
Arguments
-
value
(any): The initial value of the input.
Returns
(boolean): Defaults to false
, turns true
after the value changes and never goes back to false
.
Example
import React from 'react';
import { useValidations, useTouched } from 'form-validation-hooks';
const Input = ({ name, value, type, form, validations, handleChange }) => {
const errors = useValidations({ name, value, form, validations });
// π Get touched state.
const touched = useTouched(value);
// π Conditionally render errors.
return (
<>
<input name={name} value={value} onChange={handleChange} type={type} />
<p>
<small style={{ color: 'red' }}>{touched && errors.join(' ')}</small>
</p>
</>
)
}
export default Input;
useDirty(value)
Arguments
-
value
(any): The initial value of the input.
Returns
(boolean): Defaults to false
, turns true
after the value changes and goes back to true
if
the value returns to its initial value.
Example
import React from 'react';
import { useValidations, useDirty } from 'form-validation-hooks';
const Input = ({ name, value, type, form, validations, handleChange }) => {
const errors = useValidations({ name, value, form, validations });
// π Get dirty state.
const dirty = useDirty(value);
// π Conditionally render errors.
return (
<>
<input name={name} value={value} onChange={handleChange} type={type} />
<p>
<small style={{ color: 'red' }}>{dirty && errors.join(' ')}</small>
</p>
</>
)
}
export default Input;
useInput({ name, value, validations, form })
Arguments
-
options
(object):-
name
(string): The key/name of the input being validated. -
value
(any): The value of the input. -
validations
(object): An object that specifies validations for each input. -
form
(object): Optional, the form object which holds all of the form data.
-
Returns
(object): An object containing the result of useTouched
, useDirty
, and useValidations
.
{
touched: false,
dirty: false,
errors: {
email: [],
}
}
Example
import React from 'react';
import { useInput } from 'form-validation-hooks';
const Input = ({ name, value, type, form, validations, handleChange }) => {
// π Get input state.
const input = useInput({ name, value, form, validations });
// π Conditionally render errors.
return (
<>
<input name={name} value={value} onChange={handleChange} type={type} />
<p>
<small style={{ color: 'red' }}>{input.dirty && input.errors.join(' ')}</small>
</p>
</>
)
}
export default Input;
Β
Examples
Sign up form
This GitHub repository shows off how to utilise form-validation-hooks and covers every feature.
https://github.com/codyeatworld/signup-form-validation-hooks