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

not-valid-react

v1.0.0-alpha.10

Published

React helpers for the not-valid validation library

Downloads

14

Readme

not-valid-react

React helpers for the not-valid validation library

Installation

npm install not-valid-react

Usage

not-valid-react provides helper components for implementing validation in your react application using the not-valid validation library.

It's intended to be opionated about the logic but unopinionated about UI. If you are using Typescript it provides strong typing for all the components and props.

ValidationProvider

This component wraps around your components and:

  • holds the state
  • runs the validation
  • keeps track of the errors

If you need to update the state based upon a value changing you can use the stateTransformers prop. These should be pure functions with no side effects. Example usage might be clearing related values when selecting an option.

Props

interface ValidationProviderProps<T> {
    initialValues?: T;                                  // inital values
    validators?: Validators<T>;                         // object with key for each property of T and value of array of ValidationFunction
    combinedValidators?: CombinedValidators<T>;         // object with custom keys and value of array of ValidationFunction
    stateTransformers?: StateTransformers<T>;           // object with key for each property of T and function to update state
    onChange?: (state: ValuesAndValid<T>) => void;
    showAllErrors?: boolean;
}

Example

Note: for optimal performance you should define the objects outside your component to avoid unnecessary re-renders

import { ValidationProvider } from "not-valid-react";

interface MyType {
    name: string;
    age: number;
}

const MyProvider = ValidationProvider.ofType<MyType>();

const MyComponent = ({ onChange }) => (
    <MyProvider
        onChange={onChange}
        initalValues={{
            name: "",
            age: null
        }}
        validators={{
            name: [/* name validators */],
            age: [/* age validators */]
        }}
        combinedValidators={{
            anything: [/* validators on overall state */]
        }}
        stateTransformers={{
            name: (value, state) => /* update state based on changes to name */
        }}
    >
        <form onSubmit={onSubmit}>
            {/* inputs etc. */}

            <input type="submit" value="Submit" />
        </form>
    </MyProvider>
);

ValidationConsumer

Props

interface ValidationConsumerProps<T, K extends keyof T> {
    prop: K;                                            // key of property on type T
    validators?: ValidationFunction<T[K]>[];            // array of ValidationFunction
    children: (props: InputProps) => React.ReactNode;   // function to render input
}

Example

import { ValidationProvider, ValidationConsumer } from "not-valid-react";

const MyProvider = ValidationProvider.ofType<MyType>();
const NameInput = ValidationConsumer.ofType<MyType, "name">();

const MyComponent = () => (
    <MyProvider
        // ...
    >
        /* ... */

        <NameInput prop="name">
            {({ value, errors, showErrors, onBlur, onChange }: InputProps) => {
                const inputOnChange: React.ChangeEventHandler<any> = (event) => onChange(event.target.value);

                return (
                    <>
                        <input value={value} onBlur={onBlur} onChange={inputOnChange} />
                        {showErrors &&
                            <ul>
                                {errors.map((error, index) => <li key={index}>{error}</li>)}
                            </ul>
                        }
                    </>
                );
            }}
        </NameInput>

        /* ... */
    </MyProvider>
);

Reducing the boilerplate

You are likely going to want the same markup for all inputs of a certain type. You can create a component to encapsulate that to make your forms a lot cleaner.

import * as React from "react";
import { requiredNumber } from "not-valid/bin/validators";
import { ValidationConsumer, KeysOfType } from "not-valid-react";

export interface NumberInputProps<T> {
    prop: keyof KeysOfType<T, number>;  // restrict property name to keys of T that are a number
    label: string;
    required?: boolean;
}

const parseNumber = (value: string): number => {
    const parsed = +value;
    return isNaN(parsed) ? null : parsed;
};

export function NumberInput<T>({ label, prop }: NumberInputProps<T>) {

    const Input = ValidationConsumer.ofType<T, any>();
    const validators = this.props.required ? [requiredNumber()] : [];

    return (
        <Input
            prop={prop}
            validators={validators as any}
        >
            {({ value, onChange, onBlur, showErrors, errors }) => {
                const changeHandler: React.ChangeEventHandler<any> = (event) => onChange(parseNumber(event.target.value));

                return (
                    <div>
                        <label>{label}</label>
                        <input value={value} onChange={changeHandler} onBlur={onBlur} />
                        {showErrors &&
                            <ul>
                                {errors.map((error, index) => <li key={index}>{error}</li>)}
                            </ul>
                        }
                    </div>
                );
            }}
        </Input>
    );
}

Then you can use it like so:

import { NumberInput } from "./NumberInput";

const MyNumberInput = NumberInput as new() => NumberInput<MyType>;

const MyComponent = () => (
    /* ... */
    <MyNumberInput prop="age" label="Age" required />
    /* ... */
);

License

Made with :sparkling_heart: by NewOrbit in Oxfordshire, and licensed under the MIT Licence