2.0.2 • Published 10 months ago

meta-validator v2.0.2

Weekly downloads
57
License
MIT
Repository
github
Last release
10 months ago

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 = "myemail@test.com";
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:

IdentifierDescription
$propertyKeyThe property key that is being validated
$propertyValueThe value of the property that is being validated
$optionAny 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

DecoratorDescription
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)
2.0.2

10 months ago

2.0.1

2 years ago

2.0.0

2 years ago

2.0.0-beta.1

2 years ago

1.0.0

2 years ago

0.0.56

2 years ago

0.0.55

2 years ago

0.0.53

3 years ago

0.0.54

3 years ago

0.0.52

3 years ago

0.0.51

3 years ago

0.0.50

3 years ago

0.0.48

3 years ago

0.0.49

3 years ago

0.0.47

3 years ago

0.0.45

3 years ago

0.0.46

3 years ago

0.0.44

3 years ago

0.0.43

3 years ago

0.0.42

3 years ago

0.0.41

3 years ago

0.0.40

3 years ago

0.0.39

4 years ago

0.0.38

4 years ago

0.0.37

4 years ago

0.0.35

4 years ago

0.0.36

4 years ago

0.0.34

4 years ago

0.0.33

4 years ago

0.0.30

4 years ago

0.0.31

4 years ago

0.0.32

4 years ago

0.0.28

4 years ago

0.0.29

4 years ago

0.0.26

4 years ago

0.0.27

4 years ago

0.0.25

4 years ago

0.0.24

4 years ago

0.0.23

4 years ago

0.0.22

4 years ago

0.0.21

4 years ago

0.0.20

4 years ago

0.0.19

4 years ago

0.0.18

4 years ago

0.0.17

4 years ago

0.0.14

4 years ago

0.0.15

4 years ago

0.0.13

4 years ago

0.0.12

4 years ago

0.0.11

4 years ago

0.0.10

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago