1.0.0-alpha.10 • Published 6 years ago

not-valid-react v1.0.0-alpha.10

Weekly downloads
5
License
MIT
Repository
github
Last release
6 years ago

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

1.0.0-alpha.10

6 years ago

1.0.0-alpha.9

6 years ago

1.0.0-alpha.8

6 years ago

1.0.0-alpha.7

6 years ago

1.0.0-alpha.6

6 years ago

1.0.0-alpha.5

6 years ago

1.0.0-alpha.4

6 years ago

1.0.0-alpha.3

6 years ago

1.0.0-alpha.2

7 years ago

1.0.0-alpha.1

7 years ago