react-use-form-validation-hook
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

react-use-form-validation-hook

Validate react form data using a javascript proxy.

NPM JavaScript Style Guide

Install

npm install --save react-use-form-validation-hook

Example Usage

import { useFormValidation } from "react-use-form-validation-hook";

const validationRules = {
  email: (value: string) => {
    if (!value) {
      return "Email is required";
    }
    if (!/\S+@\S+\.\S+/.test(value)) {
      return "Email is invalid";
    }
    return true;
  },
  password: (value: string) => {
    if (!value) {
      return "Password is required";
    }
    if (value.length < 8) {
      return "Password must be at least 8 characters long";
    }
    return true;
  },
};

const MyForm = () => {
  const [formData, errors] = useFormValidation(
    { email: "", password: "" },
    validationRules
  );

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (Object.keys(errors).length === 0) {
      console.log("Form data:", formData);
    } else {
      console.log("Validation errors:", errors);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email:
        <input
          type="email"
          value={formData.email}
          onChange={(event) => {
            formData.email = event.target.value;
          }}
        />
        {errors.email && <span>{errors.email}</span>}
      </label>
      <label>
        Password:
        <input
          type="password"
          value={formData.password}
          onChange={(event) => {
            formData.password = event.target.value;
          }}
        />
        {errors.password && <span>{errors.password}</span>}
      </label>
      <button type="submit">Submit</button>
    </form>
  );
};

export default function App() {
  return <MyForm />;
}

License

MIT © BrianARuff

react-use-form-validation-hook

Readme

Keywords

none

Package Sidebar

Install

npm i react-use-form-validation-hook

Weekly Downloads

0

Version

1.0.4

License

MIT

Unpacked Size

12.6 kB

Total Files

9

Last publish

Collaborators

  • brff19