1
1
# class-validator
2
2
3
- Allows to use decorator and non-decorator based validation. Internally uses [ validator.js] [ 1 ] to perform validation.
3
+ Allows use of decorator and non-decorator based validation. Internally uses [ validator.js] [ 1 ] to perform validation.
4
4
5
5
## Installation
6
6
@@ -67,7 +67,7 @@ validate(post).then(errors => { // errors is an array of validation errors
67
67
## Validation messages
68
68
69
69
You can specify validation message in the decorator options and that message will be returned in ` ValidationError `
70
- returned by ` validate ` method in the case if validation for this field fail .
70
+ returned by ` validate ` method in the case that validation for this field fails .
71
71
72
72
``` typescript
73
73
import {MinLength , MaxLength } from " class-validator" ;
@@ -85,9 +85,9 @@ export class Post {
85
85
```
86
86
87
87
There are few special tokens you can use in your messages:
88
- * ` $value ` - the value that is being validated right now
89
- * ` $property ` - name of the object's property being validated right now
90
- * ` $target ` - name of the object's class being validated right now
88
+ * ` $value ` - the value that is being validated
89
+ * ` $property ` - name of the object's property being validated
90
+ * ` $target ` - name of the object's class being validated
91
91
* ` $constraint1 ` , ` $constraint2 ` , ... ` $constraintN ` - constraints defined by specific validation type
92
92
93
93
Example of usage:
@@ -117,9 +117,9 @@ export class Post {
117
117
@MinLength (10 , {
118
118
message : (args : ValidationArguments ) => {
119
119
if (args .value .length === 1 ) {
120
- return " Too short, minimal length is 1 character" ;
120
+ return " Too short, minimum length is 1 character" ;
121
121
} else {
122
- return " Too short, minimal length is " + args .constraints [0 ] + " characters" ;
122
+ return " Too short, minimum length is " + args .constraints [0 ] + " characters" ;
123
123
}
124
124
}
125
125
})
@@ -128,13 +128,11 @@ export class Post {
128
128
```
129
129
130
130
Message function accepts ` ValidationArguments ` which contains following information:
131
- * ` value ` - the value that is being validated right now
131
+ * ` value ` - the value that is being validated
132
132
* ` constraints ` - array of constraints defined by specific validation type
133
- * ` targetName ` - name of the object's class being validated right now
133
+ * ` targetName ` - name of the object's class being validated
134
134
* ` object ` - object that is being validated
135
- * ` property ` - name of the object's property being validated right now
136
-
137
- Values are being passed to this function, so
135
+ * ` property ` - name of the object's property being validated
138
136
139
137
## Validating arrays
140
138
@@ -157,8 +155,8 @@ This will validate each item in `post.tags` array.
157
155
158
156
## Validating nested objects
159
157
160
- If your object contains nested objects and you want validator to perform their validation too, then you need to
161
- use ` @ValidateNested() ` decorator:
158
+ If your object contains nested objects and you want the validator to perform their validation too, then you need to
159
+ use the ` @ValidateNested() ` decorator:
162
160
163
161
``` typescript
164
162
import {ValidateNested } from " class-validator" ;
@@ -176,7 +174,7 @@ export class Post {
176
174
Sometimes you may want to skip validation of the properties that does not exist in the validating object. This is
177
175
usually desirable when you want to update some parts of the object, and want to validate only updated parts,
178
176
but skip everything else, e.g. skip missing properties.
179
- In such situations you need to pass a special flag to ` validate ` method:
177
+ In such situations you will need to pass a special flag to ` validate ` method:
180
178
181
179
``` typescript
182
180
import {validate } from " class-validator" ;
@@ -232,9 +230,9 @@ validate(user, {
232
230
233
231
## Custom validation classes
234
232
235
- If you have custom validation logic you have a way to do it - you can create a * Constraint class* :
233
+ If you have custom validation logic you can create a * Constraint class* :
236
234
237
- 1 . First create a file, lets say ` CustomTextLength.ts ` , and create there a new class:
235
+ 1 . First create a file, lets say ` CustomTextLength.ts ` , and define a new class:
238
236
239
237
``` typescript
240
238
import {ValidatorConstraint , ValidatorConstraintInterface , ValidationArguments } from " class-validator" ;
@@ -258,12 +256,12 @@ If you have custom validation logic you have a way to do it - you can create a *
258
256
If you will not supply a constraint name - it will be auto -generated .
259
257
260
258
Our class must implement `ValidatorConstraintInterface ` interface and its `validate ` method ,
261
- which defines validation logic . If validation succeed method return true , otherwise false .
259
+ which defines validation logic . If validation succeeds , method returns true , otherwise false .
262
260
Custom validator can be asynchronous , if you want to perform validation after some asynchronous
263
261
operations , simply return a promise with boolean inside in `validate ` method .
264
262
265
263
Also we defined optional method `defaultMessage ` which defines a default error message ,
266
- in the case if decorator 's user didn 't set error message .
264
+ in the case that the decorator 's implementation doesn 't set an error message .
267
265
268
266
269
267
2. Then you can use your new validation constraint in your class :
@@ -294,7 +292,7 @@ If you have custom validation logic you have a way to do it - you can create a *
294
292
});
295
293
` ` `
296
294
297
- You can also send constraints to your validator , like this :
295
+ You can also pass constraints to your validator , like this :
298
296
299
297
` ` ` typescript
300
298
import {Validate} from "class-validator";
@@ -328,16 +326,16 @@ export class CustomTextLength implements ValidatorConstraintInterface {
328
326
## Custom validation decorators
329
327
330
328
You can also create a custom decorators . Its the most elegant way of using a custom validations .
331
- Lets create a decorator called ` @IsLongerThen ` :
329
+ Lets create a decorator called ` @IsLongerThan ` :
332
330
333
331
1. Create a decorator itself :
334
332
335
333
` ` ` typescript
336
334
import {registerDecorator, ValidationOptions} from "class-validator";
337
335
338
- export function IsLongerThen (property: string, validationOptions?: ValidationOptions) {
336
+ export function IsLongerThan (property: string, validationOptions?: ValidationOptions) {
339
337
return function (object: Object, propertyName: string) {
340
- registerDecorator(object, propertyName, validationOptions, [property], "is_longer_then ", (value, args) => {
338
+ registerDecorator(object, propertyName, validationOptions, [property], "is_longer_than ", (value, args) => {
341
339
const [relatedPropertyName] = args.constraints;
342
340
const relatedValue = (args.object as any)[relatedPropertyName];
343
341
return typeof value === "string" &&
@@ -348,18 +346,18 @@ Lets create a decorator called `@IsLongerThen`:
348
346
}
349
347
` ` `
350
348
351
- 2. Put it on use :
349
+ 2. Put it to use :
352
350
353
351
` ` ` typescript
354
- import {IsLongerThen } from "./IsLongerThen ";
352
+ import {IsLongerThan } from "./IsLongerThan ";
355
353
356
354
export class Post {
357
355
358
356
title: string;
359
357
360
- @IsLongerThen ("title", {
358
+ @IsLongerThan ("title", {
361
359
/* you can also use additional validation options, like "each", "groups" in your custom validation decorators */
362
- message: "Text must be longer the title"
360
+ message: "Text must be longer than the title"
363
361
})
364
362
text: string;
365
363
@@ -393,15 +391,15 @@ Lets create another custom validation decorator called `IsUserAlreadyExist`:
393
391
}
394
392
` ` `
395
393
396
- 2. And put it on use :
394
+ 2. And put it to use :
397
395
398
396
` ` ` typescript
399
397
import {IsUserAlreadyExist} from "./IsUserAlreadyExist";
400
398
401
399
export class User {
402
400
403
401
@IsUserAlreadyExist({
404
- message: "User $value already exist . Choose another name."
402
+ message: "User $value already exists . Choose another name."
405
403
})
406
404
name: string;
407
405
@@ -455,8 +453,8 @@ validator.isInt(value); // Checks if value is an integer.
455
453
validator.isDivisibleBy(value, num); // Checks if value is a number that's divisible by another.
456
454
validator.isPositive(value); // Checks if the value is a positive number.
457
455
validator.isNegative(value); // Checks if the value is a negative number.
458
- validator.max(num, max); // Checks if the first number is greater then second.
459
- validator.min(num, min); // Checks if the first number is less then second.
456
+ validator.max(num, max); // Checks if the first number is greater than second.
457
+ validator.min(num, min); // Checks if the first number is less than second.
460
458
461
459
// date validation methods
462
460
validator.minDate(date, minDate); // Checks if the value is a date that's after the specified date.
@@ -498,16 +496,16 @@ validator.isURL(str, options); // Checks if the string is an url.
498
496
validator.isUUID(str, version); // Checks if the string is a UUID (version 3, 4 or 5).
499
497
validator.isUppercase(str); // Checks if the string is uppercase.
500
498
validator.length(str, min, max); // Checks if the string's length falls in a range.
501
- validator.minLength(str, min); // Checks if the string's length is not less then given number.
502
- validator.maxLength(str, max); // Checks if the string's length is not more then given number.
499
+ validator.minLength(str, min); // Checks if the string's length is not less than given number.
500
+ validator.maxLength(str, max); // Checks if the string's length is not more than given number.
503
501
validator.matches(str, pattern, modifiers); // Checks if string matches the pattern. Either matches('foo', /foo/i) or matches('foo', 'foo', 'i').
504
502
505
503
// array validation methods
506
504
validator.arrayContains(array, values); // Checks if array contains all values from the given array of values.
507
505
validator.arrayNotContains(array, values); // Checks if array does not contain any of the given values.
508
506
validator.arrayNotEmpty(array); // Checks if given array is not empty.
509
- validator.arrayMinSize(array, min); // Checks if array's length is as minimal this number.
510
- validator.arrayMaxSize(array, max); // Checks if array's length is as maximal this number.
507
+ validator.arrayMinSize(array, min); // Checks if array's length is at least ` min ` number.
508
+ validator.arrayMaxSize(array, max); // Checks if array's length is as most ` max ` number.
511
509
validator.arrayUnique(array); // Checks if all array's values are unique. Comparison for objects is reference-based.
512
510
` ` `
513
511
@@ -533,8 +531,8 @@ validator.arrayUnique(array); // Checks if all array's values are unique. Compar
533
531
| ` @IsDivisibleBy(num: number) ` | Checks if the value is a number that ' s divisible by another. |
534
532
| ` @IsPositive() ` | Checks if the value is a positive number . |
535
533
| ` @IsNegative() ` | Checks if the value is a negative number . |
536
- | ` @Max(max: number) ` | Checks if the given number is greater then given number . |
537
- | ` @Min(min: number) ` | Checks if the given number is less then given number . |
534
+ | ` @Max(max: number) ` | Checks if the given number is greater than given number . |
535
+ | ` @Min(min: number) ` | Checks if the given number is less than given number . |
538
536
| ** Date validation decorators ** |
539
537
| ` @MinDate(date: Date) ` | Checks if the value is a date that ' s after the specified date. |
540
538
| ` @MaxDate(date: Date) ` | Checks if the value is a date that ' s before the specified date. | |
@@ -574,8 +572,8 @@ validator.arrayUnique(array); // Checks if all array's values are unique. Compar
574
572
| `@IsUUID(version?: "3"|"4"|"5")` | Checks if the string is a UUID (version 3, 4 or 5). |
575
573
| `@IsUppercase()` | Checks if the string is uppercase. |
576
574
| `@Length(min: number, max?: number)` | Checks if the string's length falls in a range. |
577
- | `@MinLength(min: number)` | Checks if the string's length is not less then given number. |
578
- | `@MaxLength(max: number)` | Checks if the string's length is not more then given number. |
575
+ | `@MinLength(min: number)` | Checks if the string's length is not less than given number. |
576
+ | `@MaxLength(max: number)` | Checks if the string's length is not more than given number. |
579
577
| `@Matches(pattern: RegExp, modifiers?: string)` | Checks if string matches the pattern. Either matches('foo', /foo/i) or matches('foo', 'foo', 'i'). |
580
578
| **Array validation decorators** |
581
579
| `@ArrayContains(values: any[])` | Checks if array contains all values from the given array of values. |
0 commit comments