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

react-class-validator

v1.4.0

Published

React hook for validation with class-validator

Downloads

1,518

Readme

react-class-validator

Easy-to-use React hook for validating forms with the class-validator library.

Build Status codecov

Installation

npm install --save react-class-validator

const validatorOptions: ValidatorContextOptions = {
    onErrorMessage: (error): string => {
        // custom error message handling (localization, etc)
    },
    resultType: 'boolean' // default, can also be set to 'map'
}

render((
    <ValidatorProvider options={validatorOptions}>
        <MyComponent />
    </ValidatorProvider>
), document.getElementById('root'))

Default onErrorMessage behavior

The default behavior is to flatten all error constraints for each attribute.

const getDefaultContextOptions = (): ValidatorContextOptions => ({
    onErrorMessage: (error) => Object.keys(error.constraints).map((key) => error.constraints[key])
});

react-intl

When using libraries such as react-intl, you don't have to modify the existing onErrorMessage handler. Decorators are handled at source load, so you only need to include the intl.formatMessage in your message definition.

class Person {

    @IsEmail({}, {
        message: intl.formatMessage(defineMessage({defaultMessage: 'Invalid email'}))
    })
    @IsNotEmpty({
        message: intl.formatMessage(defineMessage({defaultMessage: 'Email cannot be empty'}))
    })
    public email: string;
    
}

Usage

Create a class using validation decorators from class-validator.

import { IsNotEmpty } from "class-validator";

class LoginValidation {

    @IsNotEmpty({
        message: 'username cannot be empty'
    })
    public username: string;

    @IsNotEmpty({
        message: 'password cannot be empty'
    })
    public password: string;

}

Set up your form component to validate using your validation class.

const MyComponent = () => {

    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    const [validate, errors] = useValidation(LoginValidation);

    return (
        <form onSubmit={async (evt) => {

            evt.preventDefault();

            // `validate` will return true if the submission is valid
            if (await validate({username, password})) {
                // ... handle valid submission
            }

        }}>

            {/* use a filter so that the onBlur function will only validate username */}
            <input value={username} onChange={({target: {value}}) => setUsername(value)}
                onBlur={() => validate({username}, ['username'])}/>

            {/* show error */}
            {errors.username && (
                <div className="error">
                    {errors.username.map((message) => <strong>message</strong>)}
                </div>
            )}

        </form>
    );

};

Usage With Formik

react-class-validator easily integrates with Formik. You can simply use the validate function returned from useValidation, so long as the Formik fields are named the same as the keys in your validation class. Individual fields will have to be validated with onBlur functionality.

Formik error messages

To display error messages without custom handling, messages will need to be outputted as a map upon validation. Do this by overriding the default resultType (you can also do this at the component-level).

const options: ValidatorContextOptions = {
    resultType: 'map'
};

Then you can simply integrate with the default Formik flow.

export const Login: FunctionComponent = () => {

    const [validate] = useValidation(LoginValidation);

    return (
        <Formik initialValues={{username: '', password: ''}}
                validateOnBlur
                validateOnChange
                validate={validate}>
            {({values, touched, errors, handleChange, handleBlur}) => (
                <Form>
                    
                    <label htmlFor="username">Username</label>
                    <Field id="username" name="username" placeholder="Username" />

                    {errors.username && touched.username ? (
                        <div>{errors.username}</div>
                    ) : null}
                    
                    {/* other fields */}
                    
                    <button type="submit">
                        Submit
                    </button>
                    
                </Form>
            )}
        </Formik>
    );
};

Contributors

Library built and maintained by Robin Schultz

If you would like to contribute (aka buy me a beer), you can send funds via PayPal at the link below.

paypal