use-validity-state
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

use-validity-state

Build Status codecov Known Vulnerabilities Dev Dependencies Status Minified Bundle Size

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] = useState('');
  const [textareaState, setTextareaState] = useState('');
 
  const inputRef = useRef(null);
  const textareaRef = useRef(null);
 
  const validity = useValidityState({
    input: inputRef,
    textarea: textareaRef,
  });
 
  return (
    <form>
      <input
        type="text"
        value={inputState}
        onChange={(e) => setInputState(e.target.value)}
        required
        pattern="[0-9]+"
        ref={inputRef}
      />
 
      <textarea
        value={textareaState}
        onChange={(e) => setTextareaState(e.target.value)}
        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

Dependencies (0)

    Dev Dependencies (18)

    Package Sidebar

    Install

    npm i use-validity-state

    Weekly Downloads

    0

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    6.67 kB

    Total Files

    5

    Last publish

    Collaborators

    • christianguertler