项目作者: sumedh22

项目描述 :
React hook for sync and async validation in forms
高级语言: JavaScript
项目地址: git://github.com/sumedh22/react-validation-hook.git
创建时间: 2020-02-03T02:52:32Z
项目社区:https://github.com/sumedh22/react-validation-hook

开源协议:

下载


react-validation-hook

React hook for sync and async validation in forms

NPM JavaScript Style Guide

Website

Visit the website for demo and docs

Features

  • Nice and Easy hook based interface
  • Supports both Synchronous and Asynchronous validation
  • Supports validators like range, required, length, regex out of the box
  • Specify custom validators!
  • Out of the box formatted error messages, which could be overwritten

Install

  1. npm install --save react-validation-hook

Usage

  1. import React, { useEffect } from "react";
  2. import {
  3. useValidator,
  4. requiredValidation,
  5. lengthValidation,
  6. asyncValidation
  7. } from "react-validation-hook";
  8. export default () => {
  9. const asyncFunction = async (value, context) => {
  10. const response = await fetch("https://jsonplaceholder.typicode.com/photos");
  11. const res = await response.json();
  12. if (value.length < 3) {
  13. throw new Error("Custom error " + value);
  14. }
  15. };
  16. const validators = [
  17. requiredValidation(),
  18. lengthValidation(2, 5),
  19. asyncValidation(asyncFunction)
  20. ];
  21. const { error, onChange, pending } = useValidator(validators);
  22. const changeHandler = e => {
  23. console.log(e.target.value);
  24. };
  25. return (
  26. <div>
  27. <ul>
  28. {error.map((err, idx) => (
  29. <li key={idx}>{err}</li>
  30. ))}
  31. </ul>
  32. <input onChange={onChange(changeHandler)} />
  33. </div>
  34. );
  35. };

License

MIT © sumedh22