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 🙏

© 2024 – Pkg Stats / Ryan Hefner

form-validator-hook

v0.2.7

Published

A simple form validator for React based in hooks.

Downloads

2

Readme

Form Validator Hookc (FVH)

A simple form validator for React based in hooks.

FVH use a state local or context for define the input rules, then the onChange and onSubmit events do the work along with FVH hook.

Install

npm install --save form-validator-hook or yarn add form-validator-hook

Basic Usage

import React, { useState } from 'react';
import useFormValidator from 'form-validator-hook'

function App() {
  const { typeValidator, requiredValidator } = useFormValidator();
  const [state, setState] = useState({
    valid: false,
    number: {
      valid: true,
      value: '',
      type: 'number',
      rules: {
        format: 'int',
      },
    },
    text: {
      valid: true,
      value: '',
      type: 'text',
      rules: {
        maxSize: 20,
        minSize: 5,
      },
    },
    pattern: {
      valid: true,
      required: true,
      value: '',
      type: 'pattern',
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
      rules: {
        maxSize: 10,
        minSize: 5,
      },
    },
  });

  console.log(state);

  const handleChange = (e) => {
    const { target } = e;
    const status = typeValidator(target, state);
    setState(status);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const { target } = e;
    const status = requiredValidator(target, state);
    setState(status);
  };

  const { number, text, pattern } = state;

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <div>
          <label>Number</label>
          <input name="number" onChange={handleChange} value={number.value} />
          <div>{ number.errorMessage }</div>
        </div>
        <div>
          <label>Text</label>
          <input type="text" name="text" onChange={handleChange} value={text.value} />
          <div>{ text.errorMessage }</div>
        </div>
        <div>
          <label>Pattern (email example)</label>
          <input type="text" name="pattern" onChange={handleChange} value={pattern.value} />
          <div>{ pattern.errorMessage }</div>
        </div>
        <div>
          <button type="submit">Validate</button>
        </div>
      </form>
    </div>
  );
}

export default App;

IMPORTANT: The name field declared in the state should be the same that "name" property of input element.

Hook Methods

Both methods are available in the hook. There examples are based in basic usage (above)

/* ...more code above, this is only a piece of code */
import useFormValidator from 'form-validator-hook'

function NameFunction() {
	const { typeValidator, requiredValidator } = useFormValidator();
/* more code down... */

typeValidator(target, state)

This validate the field type by the onChange event, its important to know that this method recibe two obligatory args: the target prop of input and the state of form fields. See the down example with a handle arrow function:

const handleChange = (event) => {
    const { target } = event; // target destructuring (this is the input target)
    const status = typeValidator(target, state); // hook response
    setState(status); // set state with new validations obtains from typeValidator
  };

Call the handleChange function from input element and get the current value (use destructuring for get the field from state):

<input type="text" name="text" onChange={handleChange} value={text.value} />

VERY IMPORTANT: the method take the name prop of input element to search the corresponding field in the state. So, the name should be the same in the state and in the input

requiredValidator(target, state)

This validate the required fields, also it's check if all values are valids before to do the submit. This method is invoked in the onSubmit event, its important to know that this method recibe two obligatory args: the target prop of submit event and the state of form fields. See the down example with a handle arrow function:

const handleSubmit = (event) => {
    e.preventDefault(); // important for not send the form
    const { target } = event; // target of submit event
    const status = requiredValidator(target, state); // hook response
    setState(status); // set new validations
  };

Call the handleSubmit function:

<form onSubmit={handleSubmit}>

Invoke the handleSubmit function (button inside form):

<button type="submit">Validate</button>

Know if form is valid:

console.log(state.valid)

Response of the methods

Both methods response with the same structure (the declared state) but with different values. So, here are a little response example based in the example of Basic Usage section:

{
	valid: false,
	errorMessage: "There are some fields with invalid values",
	errors: ["invalidFields"],
	text: {
		errorMessage: ""
		errors: []
		required: true
		rules: {maxSize: 20, minSize: 5}
		toWrite: 15
		type: "text"
		valid: true
		value: "1111a"
	},
	number: {...}
	pattern: {...}
}

Like you see the response is very similar to the declared state, but the values changed even are added some.

Important attributes of the response.

For form:

For inputs elements:

Coming soon

  • Password validator