npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

use-react-form-validation

v1.0.0

Published

A simple React custom hook for form validation built by Rajnish Bharti.

Downloads

2

Readme

🚀 use-react-form-validation

use-react-form-validation is a lightweight, reusable React hook designed by Rajnish Bharti to simplify form state management and validation in React applications. It helps developers handle form inputs, perform real-time validation, and submit form data easily — with automatic error handling.

✅ Key Features

  • Centralized form state management
  • Real-time field validation (text, password, email, number, date, file, select, checkbox, radio, textarea)
  • Related field validation (e.g., check-in/check-out date relationship)
  • Predefined validations for mobileNo, telePhone, pinCode, email format, etc.
  • Easy integration into any React form
  • Reactive state for form data and validation errors
  • Simple submit handler returning true/false based on validation

⚡️ Installation

npm install use-react-form-validation

📚 Predefined Numeric Validation Keys

| Key Name | Description | |------------|--------------------------------------| | mobileNo | Validates as a valid mobile number (numbers only) | | telePhone | Validates as a valid telephone number (numbers only) | | pinCode | Validates as a valid postal code (numbers only) |

📚 Hook Methods & Properties

| Property / Method | Description | |------------------|-------------| | formData | Returns current form values. Example:js { user: "John", email: "[email protected]", mobileNo: "1234567890" } | | validError | Returns validation errors per field. Example:js { email: "email is required", password: "password must be at least 6 characters" } | | handleInput | Handles input changes and updates form state. Example:jsx <input type="email" name="email" value={formData.email} onChange={handleInput} placeholder="Email" /> | | handlerSubmit | Validates all fields and returns true if valid, else false. Example:js const submitForm = () => { if(handlerSubmit()) { console.log('Form is valid:', formData); } else { console.log('Validation errors:', validError); } } |

🚀 How to Use

Step 1: Import the Hook

import { useErrorHandler } from 'use-react-form-validation';

Step 2: Define Form Fields and Schema

const formFields = [
  { label: "User", type: "text", name: "user", placeholder: "User", required: false },
  { label: "Password", type: "password", name: "password", placeholder: "Password", required: true },
  { label: "Email", type: "email", name: "email", placeholder: "Email", required: true },
  { label: "Mobile No", type: "number", name: "mobileNo", placeholder: "Mobile No", required: true },
  { label: "TelePhone", type: "number", name: "telePhone", placeholder: "TelePhone", required: false },
  { label: "Pin Code", type: "number", name: "pinCode", placeholder: "Pin Code", required: true },
  { label: "Description", type: "textarea", name: "description", placeholder: "Description", required: true },
  { label: "Agree Terms", type: "checkbox", name: "agreeTerms", required: true },
  { label: "Gender", type: "radio", name: "gender", options: ["male", "female"], required: true },
  { label: "Country", type: "select", name: "country", options: ["India", "USA"], required: true },
  { label: "Check-In", type: "date", name: "checkIn", required: true },
  { label: "Check-Out", type: "date", name: "checkOut", required: true, relatedKey: "checkIn" },
  { label: "Resume", type: "file", name: "resume", required: false },
];

const formSchema = formFields.reduce((schema, field) => {
  schema[field.name] = { type: field.type, required: field.required, relatedKey: field.relatedKey };
  return schema;
}, {});

Step 3: Initialize the Hook

const { formData, validError, handleInput, handlerSubmit } = useErrorHandler(formSchema);

Step 4: Render Form Fields

<div>
  {formFields.map((field) => (
    <div key={field.name}>
      {renderField(field)}

      {validError[field.name] && (
        <p style={{ color: 'red' }}>{validError[field.name]}</p>
      )}
    </div>
  ))}

  <button onClick={() => {
    if (handlerSubmit()) console.log('Valid:', formData);
    else console.log('Errors:', validError);
  }}>
    Submit
  </button>
</div>

✅ Full Example Usage

import { useErrorHandler } from 'use-react-form-validation';

export default function User() {
  const formFields = [
    { label: "User", type: "text", name: "user", placeholder: "User", required: false },
    { label: "Password", type: "password", name: "password", placeholder: "Password", required: true },
    { label: "Email", type: "email", name: "email", placeholder: "Email", required: true },
    { label: "Mobile No", type: "number", name: "mobileNo", placeholder: "Mobile No", required: true },
    { label: "TelePhone", type: "number", name: "telePhone", placeholder: "TelePhone", required: false },
    { label: "Pin Code", type: "number", name: "pinCode", placeholder: "Pin Code", required: true },
    { label: "Description", type: "textarea", name: "description", placeholder: "Description", required: true },
    { label: "Agree Terms", type: "checkbox", name: "agreeTerms", required: true },
    { label: "Gender", type: "radio", name: "gender", options: ["male", "female"], required: true },
    { label: "Country", type: "select", name: "country", options: ["India", "USA"], required: true },
    { label: "Check-In", type: "date", name: "checkIn", required: true },
    { label: "Check-Out", type: "date", name: "checkOut", required: true, relatedKey: "checkIn" },
    { label: "Resume", type: "file", name: "resume", required: false },
  ];

  const formSchema = formFields.reduce((schema, field) => {
    schema[field.name] = { type: field.type, required: field.required, relatedKey: field.relatedKey };
    return schema;
  }, {});

  const { formData, validError, handleInput, handlerSubmit } = useErrorHandler(formSchema);

  const submitForm = () => {
    if (handlerSubmit()) {
      console.log("Form Submitted:", formData);
    } else {
      console.log("Validation Errors:", validError);
    }
  };

  const renderField = (field) => {
    switch (field.type) {
      case "text":
      case "password":
      case "email":
      case "number":
      case "date":
        return (
          <input
            type={field.type}
            name={field.name}
            value={formData[field.name]}
            onChange={handleInput}
            placeholder={field.placeholder}
            className="border p-2"
          />
        );
      case "textarea":
        return (
          <textarea
            name={field.name}
            value={formData[field.name]}
            onChange={handleInput}
            placeholder={field.placeholder}
            className="border p-2"
          />
        );
      case "checkbox":
        return (
          <label className="flex items-center gap-2">
            <input
              type="checkbox"
              name={field.name}
              checked={formData[field.name]}
              onChange={handleInput}
            />{" "}
            {field.label}
          </label>
        );
      case "radio":
        return (
          <div>
            <p>{field.label}:</p>
            {field.options.map((option) => (
              <label className="ml-2" key={option}>
                <input
                  type="radio"
                  name={field.name}
                  value={option}
                  checked={formData[field.name] === option}
                  onChange={handleInput}
                />{" "}
                {option}
              </label>
            ))}
          </div>
        );
      case "select":
        return (
          <select
            name={field.name}
            value={formData[field.name]}
            onChange={handleInput}
            className="border p-2"
          >
            <option value="">Select {field.label}</option>
            {field.options.map((option) => (
              <option key={option} value={option}>
                {option}
              </option>
            ))}
          </select>
        );
      case "file":
        return (
          <input
            type="file"
            name={field.name}
            onChange={handleInput}
            className="border p-2"
          />
        );
      default:
        return null;
    }
  };

  return (
    <div className="flex flex-col gap-4 w-96 mx-auto mt-8">
      {formFields.map((field) => (
        <div key={field.name}>
          {renderField(field)}
          {validError[field.name] && (
            <p className="text-red-500">{validError[field.name]}</p>
          )}
        </div>
      ))}
      <button
        onClick={submitForm}
        className="bg-blue-500 text-white p-2 mt-2"
      >
        Submit
      </button>
    </div>
  );
}

✅ License

© Rajnish Bharti — This package works only in React projects.