Gathering detailed insights and metrics for react-use-validation
Gathering detailed insights and metrics for react-use-validation
Gathering detailed insights and metrics for react-use-validation
Gathering detailed insights and metrics for react-use-validation
airbnb-prop-types
Custom React PropType validators that we use at Airbnb.
prop-types-exact
For use with React PropTypes. Will error on any prop not explicitly specified.
form-validation-react
form-validation-react is a lightweight and easy-to-use npm library built for validating forms in React applications. With this library, you can quickly and easily add validation rules to your form inputs, including required fields, email formats, and cust
use-smart
A react hook to generate and manage your form in a smart way!
A non-intrusive validation hook for React
npm install react-use-validation
Typescript
Module System
Node Version
NPM Version
63.1
Supply Chain
93.3
Quality
75.2
Maintenance
100
Vulnerability
100
License
TypeScript (100%)
Total Downloads
3,341
Last Day
1
Last Week
7
Last Month
25
Last Year
185
Unlicense License
28 Commits
1 Watchers
1 Branches
1 Contributors
Updated on Jun 29, 2021
Latest Version
0.0.8
Package Id
react-use-validation@0.0.8
Unpacked Size
19.80 kB
Size
6.31 kB
File Count
6
NPM Version
6.14.8
Node Version
14.15.1
Cumulative downloads
Total Downloads
Last Day
0%
1
Compared to previous day
Last Week
250%
7
Compared to previous week
Last Month
150%
25
Compared to previous month
Last Year
37%
185
Compared to previous year
1
Wouldn't it be great if there was a way to validate form fields without delegating control of form state to a third party library?
react-use-validation
is a non-intrusive validation hook for React.
This hook is not a form state library.
There's no need to attach refs or spread props on input components, learn complex state management APIs, or bloat JSX with validation configuration.
true
(valid) or false
(invalid).1// Define some state
2const [str, setStr] = React.useState('')
3
4const validation = useValidation({
5 // Define a validation rule
6 // rule_name: [state_to_validate, function_that_returns_true_or_false]
7 myValidationRule: [str, s => Boolean(s.length)],
8})
9
10const onSubmit = () => {
11 // Before submitting, run validation against all rules
12 if (validation.validate()) {
13 // Submit here...
14 }
15}
16
17return (
18 <form onSubmit={onSubmit}>
19 <input
20 value={str}
21 onChange={e => {
22 // Validate a specific rule, passing an up-to-date state value
23 validation.validate('myValidationRule', e.target.value)
24 setStr(e.target.value)
25 }}
26 />
27 {/* Render a hint if validation fails for a specific rule */}
28 {validation.isInvalid('myValidationRule') && <div>{'Please enter something'}</div>}
29 </form>
30)
npm i react-use-validation
This package depends on
react
(v16.8.0 or later).
Import the hook in a component file:
1import useValidation from 'react-use-validation'
Pass a rules
object to the hook. Each property of this object defines a single validation rule:
1const rules = { 2 ruleName: [stateToValidate, validationFunction], 3} 4 5const validation = useValidation(rules)
The property key is the rule name. This key is used to run validation for a specific rule and access validation results.
A rule is defined as an array containing two elements:
true
for succesful validation or false
for failed validation).The hook returns a validate
function that can be used to run validation.
Validation can be triggered in several ways:
validate()
(with no arguments) will run validation against all rules using current state.validate('ruleName')
(passing a rule name) will run validation against the specified rule using current state.validate('ruleName', state)
(passing both a rule name and state) will run validation against the specified rule using the passed state.Alternatively, see automatic validation.
The hook returns an isValid
function and an isInvalid
function that can be used to get validation results.
For a rule "myRule":
isValid('myRule') === true
the rule is valid.isInvalid('myRule') === true
the rule is invalid.isValid('myRule') === false && isInvalid('myRule') === false
the rule has not yet been validated.For an explanation as to why results are defined in this way, see "Why two result functions?".
react-use-validation
can be configured by passing an options
object as the second argument:
1const validation = useValidation(rules, options)
Default configuration is as follows:
1{ 2 validateOnInit: false, 3 validateOnChange: false, 4}
Defaults to
false
By default, react-use-validation
does not validate on initialization (see "Why not validate on initial render?").
To validate on initialization, set validateOnInit
to true
.
Defaults to
false
By default, validation is only triggered by calling the validate
function.
For convenience, you can set rules to automatically validate every time their state values change by setting validateOnChange
to true
.
State change is detected through strict deep value equality (not referential equality).
react-use-validation
returns an object with the following members:
A function that accepts an optional rule name string
and returns a boolean
that determines if the rule/rules are valid. If a rule name is provided, only the specified rule will be checked. If no rule name is provided, all rules will be checked.
Executing this function does not run validation.
1const isValid: <TRuleKey extends keyof TRules>(ruleKey?: TRuleKey | undefined) => boolean
A function that accepts an optional rule name string
and returns a boolean
that determines if the rule/rules are invalid. If a rule name is provided, only the specified rule will be checked. If no rule name is provided, all rules will be checked.
Executing this function does not run validation.
1const isInvalid: <TRuleKey extends keyof TRules>(ruleKey?: TRuleKey | undefined) => boolean
A function that accepts an optional rule name string
and an optional value to validate the rule against, and returns a boolean
that determines if the rule/rules are valid (true
) or invalid (false
). If a rule name is provided, only the specified rule will be validated. If a value is provided, the specified rule will be validated using the supplied value. If no rule name is provided, all rules will be validated using current state values.
Executing this function runs validation and may update state.
1const validate: <TRuleKey extends keyof TRules>( 2 ruleKey?: TRuleKey | undefined, 3 state?: TRules[TRuleKey][0] | undefined 4) => boolean
The most common use-case for validation is validating form input values. Most input values are invalid (empty) by default, so validating everything on initial render means a user sees error messages before they do anything.
To make react-use-validation
easier to work with, a validation rule does not run until its state value changes from the initial value.
You can configure this with options.validateOnInit
.
As validation does not happen on initialization by default (see "Why not validate on initial render?"), a rule can be in one of three states: valid, invalid, or unvalidated.
The most common use-case for reading validation results is to render an error message or user hint. If a result had three possible values (true
, false
, or undefined
) you would need to differentiate between false
and undefined
when rendering the error:
1// Strict equality check is required 2validation.getResult('nameEntered') === false && <div>{'Enter a name'}</div>
Instead, with the current implementation we can write:
1validation.isInvalid('nameEntered') && <div>{'Enter a name'}</div>
The first example is more verbose, and may lead into the trap of writing !validation.getResult('nameEntered')
which would incorrectly render an error if validation had not run (validation result of undefined
).
The current implementation is more declarative, shorter, and easier to read.
Validating a single input is as easy as defining a validation rule, validating when state changes, and showing a hint if validation fails:
1const [name, setName] = React.useState('')
2
3const validation = useValidation({
4 // Rule only passes if name has been entered
5 nameEntered: [name, n => Boolean(n.length)],
6})
7
8return (
9 <div>
10 <label>{'Name'}</label>
11 <input
12 value={name}
13 onChange={e => {
14 // Validate using an up-to-date state value
15 validation.validate('nameEntered', e.target.value)
16 setName(e.target.value)
17 }}
18 />
19 {validation.isInvalid('nameEntered') && <div>{'Enter a name'}</div>}
20 </div>
21)
In a form where several fields require validation, we want to validate fields individually as their values change, and then validate all fields at once before submitting.
validate
returns a boolean true
for successful validation, or false
for failed validation.
Call validate
inside your onSubmit
function, or call the isValid
function or validate
function (note that calling validate
is preferred as this also triggers validation):
1const [name, setName] = React.useState('') 2const [email, setEmail] = React.useState('') 3 4const validation = useValidation({ 5 nameEntered: [name, n => Boolean(n.length)], 6 emailShape: [email, e => /.+@.+\..+/.test(e)], 7}) 8 9const onSubmit = e => { 10 e.preventDefault() 11 12 // Validate all rules before submitting 13 const isFormValid = validation.validate() 14 15 // Alternatively, check that all rules are marked as valid 16 // const isFormValid = validation.isValid() 17 18 if (isFormValid) { 19 // Submit form here... 20 } 21} 22 23return ( 24 <form onSubmit={onSubmit}> 25 <div> 26 <label>{'Name'}</label> 27 <input 28 value={name} 29 onChange={e => { 30 // Validate name on change 31 validation.validate('nameEntered', e.target.value) 32 setName(e.target.value) 33 }} 34 /> 35 {validation.isInvalid('nameEntered') && <div>{'Enter a name'}</div>} 36 </div> 37 <div> 38 <label>{'Email'}</label> 39 <input 40 value={email} 41 onChange={e => { 42 // Validate email on change 43 validation.validate('emailShape', e.target.value) 44 setEmail(e.target.value) 45 }} 46 /> 47 {validation.isInvalid('emailShape') && <div>{'Enter a valid email'}</div>} 48 </div> 49 <button>Submit</button> 50 </form> 51)
Sometimes a single rule needs to listen to multiple state values. In this case, pass both values to the rule as either an object or an array:
1const [password, setPassword] = React.useState('')
2const [confirmPassword, setConfirmPassword] = React.useState('')
3
4const validation = useValidation({
5 passwordComplexity: [password, p => p.length > 7],
6 // Pass an object containing both state values
7 passwordMatch: [{ p: password, cp: confirmPassword }, ({ p, cp }) => p === cp],
8 // An array also works
9 // passwordMatches: [[password, confirmPassword], ([p, cp]) => p === cp],
10})
11
12return (
13 <div>
14 <div>
15 <label>{'Password'}</label>
16 <input
17 value={password}
18 onChange={e => {
19 validation.validate('passwordComplexity', e.target.value)
20 setPassword(e.target.value)
21 }}
22 />
23 {validation.isInvalid('passwordComplexity') && (
24 <div>{'Password must be at least 8 characters'}</div>
25 )}
26 </div>
27 <div>
28 <label>{'Confirm Password'}</label>
29 <input
30 value={confirmPassword}
31 onChange={e => {
32 // Make sure to pass the correct state object shape
33 validation.validate('passwordMatch', { p: password, cp: e.target.value })
34 setConfirmPassword(e.target.value)
35 }}
36 />
37 {validation.isInvalid('passwordMatch') && <div>{'Password does not match'}</div>}
38 </div>
39 </div>
40)
With automatic validation, there's no need to call validate
in the onChange
function (when validating prior to form submission, validate
should still be called).
1const [name, setName] = React.useState('')
2
3const validation = useValidation(
4 {
5 nameEntered: [name, n => Boolean(n.length)],
6 },
7 {
8 // Automatic validation when state changes
9 validateOnChange: true,
10 }
11)
12
13return (
14 <div>
15 <label>{'Name'}</label>
16 <input
17 value={name}
18 // No need to call validate here
19 onChange={e => setName(e.target.value)}
20 />
21 {validation.isInvalid('nameEntered') && <div>{'Enter a name'}</div>}
22 </div>
23)
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
9 existing vulnerabilities detected
Details
Reason
Found 0/28 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2025-04-28
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More