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

use-input-validation

v1.2.0

Published

Validate your inputs easily with this react hook.

Downloads

10

Readme

use-input-validation

GitHub issues latest release dependencies bundle size

useInputValidation is a React hook for validating inputs. It makes the validation process easy and keeps your component logic clean.

Usage example

import React from "react";
import { useInputValidation } from "use-input-validation";

function Component(props) {
  // name can be destructured to: { value, setValue, error, validate, reset }
  const name = useInputValidation(
    "", // initial `value`
    "name can not be empty", // hint used as `error` if `validate` fails
    (value) => value.trim() !== "" // predicate used in `validate`
  );

  function handleSubmit(e) {
    e.preventDefault();

    // reassure that the value is valid
    if (!name.validate()) return;

    // Do submit handle stuff
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={name.value}
        onChange={(e) => name.setValue(e.target.value)}
        onBlur={name.validate}
      />
      {name.error && <span>{name.error}</span>}
      <button type="submit">Submit</button>
    </form>
  );
}

With multiple inputs

import React from "react";
import { useInputValidation } from "use-input-validation";

// Notice the use of returned hints by the validator function for passwords.
// If your validator returns non boolean values these will be used as the error
// instead of the static hint.
function isValidPassword(pw) {
  if (pw.trim().length < 12) return "Password is to short";

  // Maybe some more logic here...

  return true;
}

function Component(props) {
  const name = useInputValidation(
    "",
    "name can not be empty",
    (value) => value.trim() !== ""
  );
  const password = useInputValidation(
    "",
    "password requirements not met",
    isValidPassword
  );

  function handleSubmit(e) {
    e.preventDefault();

    // Call all validation functions first. This way all inputs are
    // validated and all errors can be updated and displayed.
    const nameValid = name.validate();
    const emailValid = password.validate();

    // Then you can make sure that all inputs are valid
    if (!(nameValid && emailValid)) return;

    // Do submit handle stuff
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={name.value}
        onChange={(e) => name.setValue(e.target.value)}
        onBlur={name.validate}
      />
      {name.error && <span>{name.error}</span>}
      <input
        type="password"
        value={password.value}
        onChange={(e) => password.setValue(e.target.value)}
        onBlur={password.validate}
      />
      {password.error && <span>{password.error}</span>}
      <button type="submit">Submit</button>
    </form>
  );
}

Warning

Do not set the value and validate in the same react render cycle.

React may not have updated the state by the time validate is executed which means a value is validated which is outdated by the time the render cycle finishes.

This should not be a problem you encounter in a typical user form szenario.

Api

function useInputValidation<V, E>(
  initialValue: V,
  staticHint: E,
  validator: (value: V) => E | boolean
): {
  value: V;
  error: E | null;
  setValue(update: V | ((prevValue: V) => V)): void;;
  validate(): boolean;
  reset(): void;
  commit(state?: V): void;
};

Parameters

  • initialValue: Initial value that is assigned to the value.
  • hint: Error hint used to replace the error if validate evaluates the value as invalid.
  • validator: Predicate used as a decider for the validate function. It can return a boolean or some hint. If a hint is returned it will be used for the error and evaluated as an invalid value. This allows you to dynamically set the error.

Return object

  • value: Value which can be applied to inputs and text-areas.
  • error: Equals the hint or returned hint from the validator if the validator return not true. Otherwise it is null. Will be null initially.
  • setValue:
  • validate: Validates the current value and sets error depending in the validation result.
  • commit: Creates a save point for reset. The save point consists of the current value or an optional, provided state. Later calling reset will reset to the latest save point.
  • reset: Resets the value to the latest save point (equals the initial value until commit is called) and the error to null.

License

This project is published under the MIT license. All contributions are welcome.