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

meta-validator

v2.0.2

Published

meta-validator

Downloads

85

Readme

GitHub npm bundle size npm

What is meta-validator?

meta-validator is a lightweight (3k gzipped), tree-shakable, zero dependency validation library that uses TypeScript decorators to define validation rules on your classes. It is isomorphic and can be used with NodeJs or in a browser.

Installation

Install the meta-validator package from npm. npm install meta-validator

Usage

Define validation rules using the available decorators. Multiple decorators can be used on each property.

export class Widget {
    @IsNotEmpty()
    @IsAlphanumeric()
    name: string;

    @IsEmail()
    email: string;
}

const myWidget = new Widget();
widget.name = "abc1234";
widget.email = "[email protected]";
const validationErrors = await new MetaValidator().validate(myWidget);

You can also validate arrays of objects in the same way.

const widgetArray: Widget[] = [];
const validationErrorArray = await new MetaValidator().validate(widgetArray);

Validation Errors

If an object fails validation then meta-validator returns a ValidationError object with the following structure.: <property>:[<array of validation error messages>] Example: { email: [ 'email must be a valid email address.' ] }

Custom Validation Error Messages

You can provide custom error messages by using the customErrorMessages option.

const validationErrors = await new MetaValidator().validate(widget, {
    customErrorMessages: {
        "IsEqualTo": "$propertyKey must be equal to $option0"
    }
});

When using custom error messages the following text replacement codes are available:

| Identifier | Description | |-----------------|-------------------------------------------------------| | $propertyKey | The property key that is being validated | | $propertyValue | The value of the property that is being validated | | $option | Any options that are passed to the validator function |

Custom Message Formatter

If you require total control over validation error messages you can supply a custom message formatter.

const validationErrors = await new MetaValidator().validate(widget, {
    customErrorMessageFormatter: (data: FormatterData) => {
        let errorMessage = data.message;
        errorMessage = errorMessage.replace("$propertyKey", sentenceCase(data.propertyKey));
        errorMessage = errorMessage.replace("$propertyValue", data.propertyValue);
    
        if (data.options) {
            for (let i = 0; i < data.options.length; i++) {
                errorMessage = errorMessage.replace(`$option${i}`, data.options[i]);
            }
        }
    
        return errorMessage;
    }
});

A custom formatter receives a parameter that has the following values:

interface FormatterData {
    decoratorName: string;   // The decorator name e.g. IsBoolean()
    message: string;         // The default validation error message
    propertyKey: string;     // The key of the property being validated
    propertyValue: string;   // The value of the property being validated
    options?: any[];         // Any options passed to the validator function
}

Skip Undefined Values

If you wish to validate an object but skip any properties with values that are undefined you can use the isSkipUndefinedValues option.

const validationErrors = await new MetaValidator().validate(widget, {isSkipUndefinedValues: true});

Custom Decorators

You can also create your own validation decorators. Use the existing decorators as examples.

export function IsIp(options?: IsIpOptions): PropertyDecorator {
    return (target, propertyKey) => {
        MetaValidator.addMetadata({
            // Metadata
            target: target,
            propertyKey: propertyKey.toString(),
            // Context
            className: target.constructor.name,
            validator: {
                decoratorName: IsIp.name,
                message: "$propertyKey must be a valid ip address.",
                method: (input: any) => {
                    return Promise.resolve(isIp(input, options));
                }
            }
        });
    };
}

Decorator Reference

| Decorator | Description | |--------------------------|-----------------------------------------------------------| | IsAlpha() | Only contains letters | | IsAlphanumeric() | Only contains letters or numbers | | IsBoolean() | Is of type boolean | | IsEmail() | Is a valid email address |
| IsEmpty() | Is null, undefined, an empty string or object |
| IsEqualTo() | Is equal to specified property |
| IsFqDn() | Is a fully qualified domain name (URL) |
| IsIp() | Is a valid v4 or v6 IP address |
| IsMaxLength() | Has a max length of x | | IsMinLength() | Has a minimum length of x |
| IsNested() | Also validate decorated child object | | IsNotEmpty() | Is not null, undefined, an empty string or object | | IsNotEqualTo() | Is not equal to specified property | | IsNumber() | Is of type number |
| IsRegEx() | Is of type Regex (regular expression) |
| IsString() | Is of type string |
| IsUrl() | Is a valid URL (uniform resource locator) |
| IsValid() | Property is always valid (useful for skipping validation) |