# @umajs/model

> model validate, class validate, model schema, json schema

Latest version **1.0.11** (published 2021-04-15) · 0 weekly downloads

## Install

```sh
npm install @umajs/model
pnpm add @umajs/model
yarn add @umajs/model
bun add @umajs/model
```

## Health

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

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.11 |
| Published | 2021-04-15 |
| First published | 2021-03-19 |
| Weekly downloads | 0 |
| TypeScript types | none |
| Module format | CommonJS |
| Node | >= 8.0 |
| Dependencies | 0 |
| Unpacked size | 13.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 9 |
| Maintainers | edwwardzzz, dazjean, bubblelm, cocoboom |
| Keywords | model, model validate, class validate, model shema, json schema |

## Links

- npm: https://www.npmjs.com/package/@umajs/model
- Repository: https://github.com/umajs/model
- Homepage: https://github.com/umajs/model#readme
- Issues: https://github.com/umajs/model/issues
- npm.io page: https://npm.io/package/@umajs/model

## Alternatives

- [vest](https://npm.io/package/vest.md) — 50.1K weekly downloads
- [@regle/core](https://npm.io/package/@regle/core.md) — 47.0K weekly downloads
- [typeof-arguments](https://npm.io/package/typeof-arguments.md) — 12.5K weekly downloads
- [@lokalise/projects-engine-contracts](https://npm.io/package/@lokalise/projects-engine-contracts.md) — 978 weekly downloads
- [@osjwnpm/nam-laboriosam-quibusdam](https://npm.io/package/@osjwnpm/nam-laboriosam-quibusdam.md) — 70 weekly downloads

## Recent versions

- 1.0.11 (latest) — 2021-04-15
- 1.0.10 — 2021-04-11
- 1.0.9 — 2021-04-06
- 1.0.8 — 2021-04-02
- 1.0.6 — 2021-04-01
- 1.0.5 — 2021-03-31
- 1.0.4 — 2021-03-29
- 1.0.3 — 2021-03-26
- 1.0.2 — 2021-03-26
- 1.0.1 — 2021-03-26
- 1.0.0 — 2021-03-26
- 0.1.0 — 2021-03-25
- 0.0.1 — 2021-03-19

## README

# @umajs/class-validator

本项目已重命名为[@umajs/class-validator](https://www.npmjs.com/package/@umajs/class-validator)

这是一个基于装饰器的校验库，通过给 class 的属性加上装饰器给属性来加上属性校验。

### Installation
```shell
npm i -S @umajs/class-validator
```

### Usage
新建 class extends Model 然后加上校验装饰器

> 【默认】继承 Model，在赋值的时候，值没通过校验的时候是不能给对应的属性赋值的，但是如果想要赋值成功，可以通过 ```super(false)``` 越过校验拦截（还是能正常拿到错误信息）

> eg1: class Info extends Model { constructor(params: Info, validBlock: boolean) { super(validBlock); } }

> eg2: class Info extends Model { constructor(params: Info) { super(false); } }

```js
import { Model, Validate, Type, Required, Min } from '@umajs/class-validator';

class UserInfo extends Model {
    constructor({ id, name, age }: UserInfo) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Type('number')
    id: number = 123;

    @Required()
    name?: string;

    @Min(0)
    age?: number;
}
```

执行 ```Validate``` 获取获取信息
```js
declare function Validate<T extends Object>(target: T, value?: T): [{
    [key: string]: string[];
}, T];
```

如下：
```js
const [info1, user] = Validate(new UserInfo({ id: 123 }));
console.log('1>>', info1);  // >> { name: [ 'not null.' ] }

// 1
const [info2] = Validate(user, { 'id': 456, age: -1 });
console.log('2>>', info2);  // >> { age: [ 'min..not lt {0}' ] }

// 2
user.id = 456;
user.name = undefined;
user.age = -2;
const [info3] = Validate(user);
console.log('3>>', info3);  // >> { name: [ 'not null.' ], age: [ 'min..not lt {0}' ] }

console.log(JSON.stringify(user));
```

### 规则 Rules
参数中可选的 message 是验证不通过的提示信息，本库提供了一套默认的提示信息，可以通过提供的 UpdateMessages 来更改默认的提示信息。

#### 修改提示信息模版 UpdateMessages
```js
export declare function UpdateMessages(params?: {
    [P in keyof RuleKeys]?: string;
}): void;
```
eg: 更改 Range 提示
```js
import { UpdateMessages } from '@umajs/class-validator';

UpdateMessages({
    Range: '值必须介于 {0} 和 {1} 之间',    // {0}{1} 为占位符，会从 Rule 的参数 ruleParams 中取值
});
```


#### 必需 Required
```js
declare function Required(message?: string): PropertyDecorator;
```

#### 类型 Type & Int
```js
export type Types = 'undefined' | 'string' | 'null' | 'number' | 'number' | 'boolean'
    | 'date' | 'function' | 'object' | 'array' | 'map' | 'set' | 'symbol' | 'function'
    | 'promise' | 'weakset' | 'weakmap' | 'generatorfunction' | 'asyncfunction' | 'object' | 'regexp';

export declare const Type: (t: Types, message?: string) => PropertyDecorator;
export declare const Int: (t: 'int8' | 'int32' | 'int64', message?: string) => PropertyDecorator;
```

#### 大小 Mix & Max & Range
```js
export declare function Min(n: number, message?: string): PropertyDecorator;
export declare function Max(n: number, message?: string): PropertyDecorator;
export declare function Range(min: number, max: number, message?: string): PropertyDecorator;
```

#### 长度 MinLength & MaxLength
```js
export declare function MinLength(n: number, message?: string): PropertyDecorator;
export declare function MaxLength(n: number, message?: string): PropertyDecorator;
```

#### 扩展规则
假设需要扩展一个 Email 规则，示例如下：
```js
export function Email(message: string = messages.MaxLength): PropertyDecorator {
    const rule = new Rule({
        ruleType: 'Email',
        ruleParams: [], // 供提示信息使用
        message: '必须为邮件格式，例如"xxx@xx.xx"',
        validate(value: any): boolean {
            if (isEmpley(value)) return true;

            return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value);
        },
    });

    return rule.add();
}
```


#### 转换提示信息格式 MessageTransform

可以通过 MessageTransform 转换提示信息。
- UpdateMessages 是更改提示信息的模版
- MessageTransform 是修改提示信息的格式，此处的提示信息是从信息模版中拿到的信息

```js
export declare function MessageTransform(transFn: (key: string, message: string, ruleType?: string, ruleParams?: any[]) => any): void;
```

```js
class UserInfo extends Model {
    constructor({ name }: UserInfo) {
        super();
        this.name = name;
    }

    @Required()
    name?: string;

}

export { MessageTransform } from '@umajs/class-validator';

MessageTransform((key: string, message: string, ruleType: string) => {
    return {
        [ruleType]: message,
    }
});

const [info1, user] = Validate(new UserInfo({}));
console.log('1>>', info1);  // >> { name: [ { Required: 'not null' } ] }
```

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