# meta-validator

> meta-validator

Latest version **2.0.2** (published 2023-08-06) · MIT license · 0 weekly downloads

## Install

```sh
npm install meta-validator
pnpm add meta-validator
yarn add meta-validator
bun add meta-validator
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.0.2 |
| Published | 2023-08-06 |
| First published | 2020-05-24 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 139.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Rob Muchall |
| Maintainers | rmuchall |
| Keywords | validation |

## Links

- npm: https://www.npmjs.com/package/meta-validator
- Repository: https://github.com/rmuchall/meta-validator
- Homepage: https://github.com/rmuchall/meta-validator#readme
- Issues: https://github.com/rmuchall/meta-validator/issues
- npm.io page: https://npm.io/package/meta-validator

## Alternatives

- [@sindresorhus/slugify](https://npm.io/package/@sindresorhus/slugify.md) — 3.7M weekly downloads
- [solid-js](https://npm.io/package/solid-js.md) — 2.7M weekly downloads
- [expo-glass-effect](https://npm.io/package/expo-glass-effect.md) — 2.5M weekly downloads
- [nanoassert](https://npm.io/package/nanoassert.md) — 780.8K weekly downloads
- [@ffmpeg/ffmpeg](https://npm.io/package/@ffmpeg/ffmpeg.md) — 529.5K weekly downloads

## Recent versions

- 2.0.2 (latest) — 2023-08-06
- 2.0.0-beta.1 (beta) — 2022-06-12
- 2.0.1 — 2022-11-04
- 2.0.0 — 2022-11-04
- 1.0.0 — 2022-05-06
- 0.0.56 — 2022-03-01
- 0.0.55 — 2022-01-07
- 0.0.54 — 2021-11-12
- 0.0.53 — 2021-11-12
- 0.0.52 — 2021-10-28
- 0.0.51 — 2021-10-24
- 0.0.50 — 2021-08-30
- 0.0.49 — 2021-08-30
- 0.0.48 — 2021-08-30
- 0.0.47 — 2021-07-31
- … 44 more at https://npm.io/package/meta-validator/versions

## README

![GitHub](https://img.shields.io/github/license/rmuchall/meta-validator)
![npm bundle size](https://img.shields.io/bundlephobia/minzip/meta-validator)
![npm](https://img.shields.io/npm/v/meta-validator)
## What is meta-validator?
meta-validator is a lightweight ([3k gzipped](https://bundlephobia.com/package/meta-validator)), [tree-shakable](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking), zero dependency validation library that uses [TypeScript decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) to define validation rules on your classes. It is isomorphic and can be used with NodeJs or in a browser.<br/>

## Installation
Install the [meta-validator package](https://www.npmjs.com/package/meta-validator) from npm. <br/>
`npm install meta-validator`

## Usage
Define validation rules using the available decorators. Multiple decorators can be used on each property.<br/>
```typescript
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.<br/>
```typescript
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.:<br/>
`<property>:[<array of validation error messages>]`<br/>
Example:<br/>
`{ email: [ 'email must be a valid email address.' ] }`<br/>

### Custom Validation Error Messages
You can provide custom error messages by using the `customErrorMessages` option.<br/>
```typescript
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:<br/>

| Identifier      | Description                                           | 
|-----------------|-------------------------------------------------------|
| $propertyKey    | The property key that is being validated              |
| $propertyValue  | The value of the property that is being validated     | 
| $option<number> | 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.<br/>
```typescript
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:<br/>
```typescript
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.<br/>
```typescript
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.<br/>
```typescript
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(<property>)    | 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(<property>) | 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) |

---
_Source: https://npm.io/package/meta-validator · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
