use-validity-state
A React hook for form validation leveraging HTML5 ValidityState API.
ValidityState
is generally widely supported but its supported features may be limited depending on the browser used.
Installation
npm install use-validity-state
or
yarn add use-validity-state
Usage
In your component, initialize the Hook using use-validity-state
like so:
const MyComponent = { const inputState setInputState = ; const textareaState setTextareaState = ; const inputRef = ; const textareaRef = ; const validity = ; return <form> <input type="text" value=inputState onChange= required pattern="[0-9]+" ref=inputRef /> <textarea value=textareaState onChange= required ref=textareaRef /> </form> ;}
Simply provide a ref
for each form element that you want to validate to useValidityState
as a key/value pair with the value being the ref
and an arbitrary key.
As the return value of useValidityState
you will receive an object containing a ValidityState
for each previously provided element. The key for each element will match the respective key you provided during the initialization of useValidityState
.
Additionally, you will get an element with the key every
containing the overall validation result. It will be false
unless every single element validation yields true
.
Use your own logic to update the value of the form element. Add the desired validation props to the element such as required
, minLength
, or pattern
. When the component is updated, the validity values get updated, reflecting the current validation state.
License
- MIT (see LICENSE)