class-validator
允许使用基于装饰器和非装饰器的验证。 内部使用validator.js执行验证。 类验证器可以在浏览器和 node.js 平台上运行。
安装¶
Note: Please use at least npm@6 when using class-validator. From npm@6 the dependency tree is flattened, which is required by
class-validator
to function properly.
使用¶
Create your class and put some validation decorators on the properties you want to validate:
传输选项¶
validate
函数的第二个参数是一个ValidatorOptions
对象。
It's highly advised to set
forbidUnknownValues: true
as it will prevent unknown objects from passing validation.
验证错误¶
' validate '方法返回一个' ValidationError '对象数组。每个“ValidationError”是:
In our case, when we validated a Post object, we have such an array of ValidationError
objects:
If you don't want a target
to be exposed in validation errors, there is a special option when you use validator:
This is especially useful when you send errors back over http, and you most probably don't want to expose the whole target object.
验证消息¶
You can specify validation message in the decorator options and that message will be returned in the ValidationError
returned by the validate
method (in the case that validation for this field fails).
There are few special tokens you can use in your messages:
$value
- the value that is being validated$property
- name of the object's property being validated$target
- name of the object's class being validated$constraint1
,$constraint2
, ...$constraintN
- constraints defined by specific validation type
Example of usage:
Also you can provide a function, that returns a message. This allows you to create more granular messages:
Message function accepts ValidationArguments
which contains the following information:
value
- the value that is being validatedconstraints
- array of constraints defined by specific validation typetargetName
- name of the object's class being validatedobject
- object that is being validatedproperty
- name of the object's property being validated
验证数组¶
If your field is an array and you want to perform validation of each item in the array you must specify a
special each: true
decorator option:
This will validate each item in post.tags
array.
验证集¶
If your field is a set and you want to perform validation of each item in the set you must specify a
special each: true
decorator option:
This will validate each item in post.tags
set.
验证图¶
If your field is a map and you want to perform validation of each item in the map you must specify a
special each: true
decorator option:
This will validate each item in post.tags
map.
验证嵌套对象¶
If your object contains nested objects and you want the validator to perform their validation too, then you need to
use the @ValidateNested()
decorator:
Please note that nested object must be an instance of a class, otherwise @ValidateNested
won't know what class is target of validation. Check also Validating plain objects.
It also works with multi-dimensional array, like :
验证承诺¶
If your object contains property with Promise
-returned value that should be validated, then you need to use the @ValidatePromise()
decorator:
It also works great with @ValidateNested
decorator:
验证继承修饰符¶
When you define a subclass which extends from another one, the subclass will automatically inherit the parent's decorators. If a property is redefined in the descendant class decorators will be applied on it both from that and the base class.
有条件的验证¶
The conditional validation decorator (@ValidateIf
) can be used to ignore the validators on a property when the provided condition function returns false. The condition function takes the object being validated and must return a boolean
.
In the example above, the validation rules applied to example
won't be run unless the object's otherProperty
is "value"
.
Note that when the condition is false all validation decorators are ignored, including isDefined
.
白名单¶
Even if your object is an instance of a validation class it can contain additional properties that are not defined.
If you do not want to have such properties on your object, pass special flag to validate
method:
This will strip all properties that don't have any decorators. If no other decorator is suitable for your property, you can use @Allow decorator:
If you would rather to have an error thrown when any non-whitelisted properties are present, pass another flag to
validate
method:
将上下文传递给装饰器¶
It's possible to pass a custom object to decorators which will be accessible on the ValidationError
instance of the property if validation failed.
跳过缺失的属性¶
Sometimes you may want to skip validation of the properties that do not exist in the validating object. This is
usually desirable when you want to update some parts of the object, and want to validate only updated parts,
but skip everything else, e.g. skip missing properties.
In such situations you will need to pass a special flag to validate
method:
When skipping missing properties, sometimes you want not to skip all missing properties, some of them maybe required
for you, even if skipMissingProperties is set to true. For such cases you should use @IsDefined()
decorator.
@IsDefined()
is the only decorator that ignores skipMissingProperties
option.
验证组¶
In different situations you may want to use different validation schemas of the same object. In such cases you can use validation groups.
There is also a special flag always: true
in validation options that you can use. This flag says that this validation
must be applied always no matter which group is used.
自定义验证类¶
If you have custom validation logic you can create a Constraint class:
- First create a file, lets say
CustomTextLength.ts
, and define a new class:
We marked our class with @ValidatorConstraint
decorator.
You can also supply a validation constraint name - this name will be used as "error type" in ValidationError.
If you will not supply a constraint name - it will be auto-generated.
Our class must implement ValidatorConstraintInterface
interface and its validate
method,
which defines validation logic. If validation succeeds, method returns true, otherwise false.
Custom validator can be asynchronous, if you want to perform validation after some asynchronous
operations, simply return a promise with boolean inside in validate
method.
Also we defined optional method defaultMessage
which defines a default error message,
in the case that the decorator's implementation doesn't set an error message.
2) Then you can use your new validation constraint in your class:
Here we set our newly created CustomTextLength
validation constraint for Post.title
.
3) And use validator as usual:
You can also pass constraints to your validator, like this:
And use them from validationArguments
object:
自定义验证修饰符¶
You can also create a custom decorators. Its the most elegant way of using a custom validations.
Lets create a decorator called @IsLongerThan
:
- Create a decorator itself:
- Put it to use:
In your custom decorators you can also use ValidationConstraint
.
Lets create another custom validation decorator called IsUserAlreadyExist
:
- Create a ValidationConstraint and decorator:
note that we marked our constraint that it will by async by adding { async: true }
in validation options.
- And put it to use:
使用服务容器¶
Validator supports service container in the case if want to inject dependencies into your custom validator constraint classes. Here is example how to integrate it with typedi:
同步验证¶
If you want to perform a simple non async validation you can use validateSync
method instead of regular validate
method. It has the same arguments as validate
method. But note, this method ignores all async validations
you have.
手动验证¶
There are several method exist in the Validator that allows to perform non-decorator based validation:
验证修饰符¶
Decorator | Description |
---|---|
Common validation decorators | |
@IsDefined(value: any) |
Checks if value is defined (!== undefined, !== null). This is the only decorator that ignores skipMissingProperties option. |
@IsOptional() |
Checks if given value is empty (=== null, === undefined) and if so, ignores all the validators on the property. |
@Equals(comparison: any) |
Checks if value equals ("===") comparison. |
@NotEquals(comparison: any) |
Checks if value not equal ("!==") comparison. |
@IsEmpty() |
Checks if given value is empty (=== '', === null, === undefined). |
@IsNotEmpty() |
Checks if given value is not empty (!== '', !== null, !== undefined). |
@IsIn(values: any[]) |
Checks if value is in a array of allowed values. |
@IsNotIn(values: any[]) |
Checks if value is not in a array of disallowed values. |
Type validation decorators | |
@IsBoolean() |
Checks if a value is a boolean. |
@IsDate() |
Checks if the value is a date. |
@IsString() |
Checks if the string is a string. |
@IsNumber(options: IsNumberOptions) |
Checks if the value is a number. |
@IsInt() |
Checks if the value is an integer number. |
@IsArray() |
Checks if the value is an array |
@IsEnum(entity: object) |
Checks if the value is an valid enum |
Number validation decorators | |
@IsDivisibleBy(num: number) |
Checks if the value is a number that's divisible by another. |
@IsPositive() |
Checks if the value is a positive number greater than zero. |
@IsNegative() |
Checks if the value is a negative number smaller than zero. |
@Min(min: number) |
Checks if the given number is greater than or equal to given number. |
@Max(max: number) |
Checks if the given number is less than or equal to given number. |
Date validation decorators | |
@MinDate(date: Date) |
Checks if the value is a date that's after the specified date. |
@MaxDate(date: Date) |
Checks if the value is a date that's before the specified date. |
String-type validation decorators | |
@IsBooleanString() |
Checks if a string is a boolean (e.g. is "true" or "false"). |
@IsDateString() |
Alias for @IsISO8601() . |
@IsNumberString(options?: IsNumericOptions) |
Checks if a string is a number. |
String validation decorators | |
@Contains(seed: string) |
Checks if the string contains the seed. |
@NotContains(seed: string) |
Checks if the string not contains the seed. |
@IsAlpha() |
Checks if the string contains only letters (a-zA-Z). |
@IsAlphanumeric() |
Checks if the string contains only letters and numbers. |
@IsDecimal(options?: IsDecimalOptions) |
Checks if the string is a valid decimal value. Default IsDecimalOptions are force_decimal=False , decimal_digits: '1,' , locale: 'en-US' |
@IsAscii() |
Checks if the string contains ASCII chars only. |
@IsBase32() |
Checks if a string is base32 encoded. |
@IsBase64() |
Checks if a string is base64 encoded. |
@IsIBAN() |
Checks if a string is a IBAN (International Bank Account Number). |
@IsBIC() |
Checks if a string is a BIC (Bank Identification Code) or SWIFT code. |
@IsByteLength(min: number, max?: number) |
Checks if the string's length (in bytes) falls in a range. |
@IsCreditCard() |
Checks if the string is a credit card. |
@IsCurrency(options?: IsCurrencyOptions) |
Checks if the string is a valid currency amount. |
@IsEthereumAddress() |
Checks if the string is an Ethereum address using basic regex. Does not validate address checksums. |
@IsBtcAddress() |
Checks if the string is a valid BTC address. |
@IsDataURI() |
Checks if the string is a data uri format. |
@IsEmail(options?: IsEmailOptions) |
Checks if the string is an email. |
@IsFQDN(options?: IsFQDNOptions) |
Checks if the string is a fully qualified domain name (e.g. domain.com). |
@IsFullWidth() |
Checks if the string contains any full-width chars. |
@IsHalfWidth() |
Checks if the string contains any half-width chars. |
@IsVariableWidth() |
Checks if the string contains a mixture of full and half-width chars. |
@IsHexColor() |
Checks if the string is a hexadecimal color. |
@IsHSLColor() |
Checks if the string is an HSL color based on CSS Colors Level 4 specification. |
@IsRgbColor(options?: IsRgbOptions) |
Checks if the string is a rgb or rgba color. |
@IsIdentityCard(locale?: string) |
Checks if the string is a valid identity card code. |
@IsPassportNumber(countryCode?: string) |
Checks if the string is a valid passport number relative to a specific country code. |
@IsPostalCode(locale?: string) |
Checks if the string is a postal code. |
@IsHexadecimal() |
Checks if the string is a hexadecimal number. |
@IsOctal() |
Checks if the string is a octal number. |
@IsMACAddress(options?: IsMACAddressOptions) |
Checks if the string is a MAC Address. |
@IsIP(version?: "4"\|"6") |
Checks if the string is an IP (version 4 or 6). |
@IsPort() |
Checks if the string is a valid port number. |
@IsISBN(version?: "10"\|"13") |
Checks if the string is an ISBN (version 10 or 13). |
@IsEAN() |
Checks if the string is an if the string is an EAN (European Article Number). |
@IsISIN() |
Checks if the string is an ISIN (stock/security identifier). |
@IsISO8601(options?: IsISO8601Options) |
Checks if the string is a valid ISO 8601 date format. Use the option strict = true for additional checks for a valid date. |
@IsJSON() |
Checks if the string is valid JSON. |
@IsJWT() |
Checks if the string is valid JWT. |
@IsObject() |
Checks if the object is valid Object (null, functions, arrays will return false). |
@IsNotEmptyObject() |
Checks if the object is not empty. |
@IsLowercase() |
Checks if the string is lowercase. |
@IsLatLong() |
Checks if the string is a valid latitude-longitude coordinate in the format lat, long. |
@IsLatitude() |
Checks if the string or number is a valid latitude coordinate. |
@IsLongitude() |
Checks if the string or number is a valid longitude coordinate. |
@IsMobilePhone(locale: string) |
Checks if the string is a mobile phone number. |
@IsISO31661Alpha2() |
Checks if the string is a valid ISO 3166-1 alpha-2 officially assigned country code. |
@IsISO31661Alpha3() |
Checks if the string is a valid ISO 3166-1 alpha-3 officially assigned country code. |
@IsLocale() |
Checks if the string is a locale. |
@IsPhoneNumber(region: string) |
Checks if the string is a valid phone numberusing libphonenumber-js. |
@IsMongoId() |
Checks if the string is a valid hex-encoded representation of a MongoDB ObjectId. |
@IsMultibyte() |
Checks if the string contains one or more multibyte chars. |
@IsNumberString(options?: IsNumericOptions) |
Checks if the string is numeric. |
@IsSurrogatePair() |
Checks if the string contains any surrogate pairs chars. |
@IsUrl(options?: IsURLOptions) |
Checks if the string is an url. |
@IsMagnetURI() |
Checks if the string is a magnet uri format. |
@IsUUID(version?: "3"\|"4"\|"5"\|"all") |
Checks if the string is a UUID (version 3, 4, 5 or all ). |
@IsFirebasePushId() |
Checks if the string is a Firebase Push ID |
@IsUppercase() |
Checks if the string is uppercase. |
@Length(min: number, max?: number) |
Checks if the string's length falls in a range. |
@MinLength(min: number) |
Checks if the string's length is not less than given number. |
@MaxLength(max: number) |
Checks if the string's length is not more than given number. |
@Matches(pattern: RegExp, modifiers?: string) |
Checks if string matches the pattern. Either matches('foo', /foo/i) or matches('foo', 'foo', 'i'). |
@IsMilitaryTime() |
Checks if the string is a valid representation of military time in the format HH:MM. |
@IsHash(algorithm: string) |
Checks if the string is a hash The following types are supported:md4 , md5 , sha1 , sha256 , sha384 , sha512 , ripemd128 , ripemd160 , tiger128 , tiger160 , tiger192 , crc32 , crc32b . |
@IsMimeType() |
Checks if the string matches to a valid MIME type format |
@IsSemVer() |
Checks if the string is a Semantic Versioning Specification (SemVer). |
@IsISSN(options?: IsISSNOptions) |
Checks if the string is a ISSN. |
@IsISRC() |
Checks if the string is a ISRC. |
@IsRFC3339() |
Checks if the string is a valid RFC 3339 date. |
Array validation decorators | |
@ArrayContains(values: any[]) |
Checks if array contains all values from the given array of values. |
@ArrayNotContains(values: any[]) |
Checks if array does not contain any of the given values. |
@ArrayNotEmpty() |
Checks if given array is not empty. |
@ArrayMinSize(min: number) |
Checks if the array's length is greater than or equal to the specified number. |
@ArrayMaxSize(max: number) |
Checks if the array's length is less or equal to the specified number. |
@ArrayUnique(identifier?: (o) => any) |
Checks if all array's values are unique. Comparison for objects is reference-based. Optional function can be speciefied which return value will be used for the comparsion. |
Object validation decorators | |
@IsInstance(value: any) |
Checks if the property is an instance of the passed value. |
Other decorators | |
@Allow() |
Prevent stripping off the property when no other constraint is specified for it. |
定义没有装饰器的验证模式¶
你可以在没有装饰器的情况下定义你的验证模式:
- you can define it in the separate object
- you can define it in the
.json
file
This feature maybe useful in the cases if:
- are using es5/es6 and don't have decorators available
- you don't have a classes, and instead using interfaces
- you don't want to use model at all
- you want to have a validation schema separate of your model
- you want beautiful json-schema based validation models
- you simply hate decorators
Here is an example of using it:
- Create a schema object:
Same schema can be provided in .json
file, depend on your wish.
- Register your schema:
Better to put this code in a global place, maybe when you bootstrap your application, for example in app.ts
.
- Validate your object using validation schema:
That's it. Here "myUserSchema"
is the name of our validation schema.
validate
method will perform validation based on this schema
验证纯对象¶
由于装饰器的特性,验证过的对象必须使用new Class()
语法进行实例化。
如果你用类验证器装饰器定义了你的类,并且你想验证普通的 JS 对象(文字对象或 JSON.parse 返回的对象),你需要通过使用class-transformer将其转换为类实例。
样品¶
请参阅./sample中的示例以获得更多用法示例。
扩展¶
有几个扩展可以简化类验证器与其他模块的集成:
- class-validator integration with class-transformer
- class-validator-rule
- ngx-dynamic-form-builder
- abarghoud/ngx-reactive-form-class-validator
发布说明¶
查看关于中断更改和发布说明的信息在这里。