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

@umajs/model

v1.0.11

Published

model validate, class validate, model schema, json schema

Downloads

4

Readme

@umajs/class-validator

本项目已重命名为@umajs/class-validator

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

Installation

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); } }

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 获取获取信息

declare function Validate<T extends Object>(target: T, value?: T): [{
    [key: string]: string[];
}, T];

如下:

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

export declare function UpdateMessages(params?: {
    [P in keyof RuleKeys]?: string;
}): void;

eg: 更改 Range 提示

import { UpdateMessages } from '@umajs/class-validator';

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

必需 Required

declare function Required(message?: string): PropertyDecorator;

类型 Type & Int

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

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

export declare function MinLength(n: number, message?: string): PropertyDecorator;
export declare function MaxLength(n: number, message?: string): PropertyDecorator;

扩展规则

假设需要扩展一个 Email 规则,示例如下:

export function Email(message: string = messages.MaxLength): PropertyDecorator {
    const rule = new Rule({
        ruleType: 'Email',
        ruleParams: [], // 供提示信息使用
        message: '必须为邮件格式,例如"[email protected]"',
        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 是修改提示信息的格式,此处的提示信息是从信息模版中拿到的信息
export declare function MessageTransform(transFn: (key: string, message: string, ruleType?: string, ruleParams?: any[]) => any): void;
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' } ] }