1 | # class-validator
|
2 |
|
3 | ![Build Status](https://github.com/typestack/class-validator/workflows/CI/badge.svg)
|
4 | [![codecov](https://codecov.io/gh/typestack/class-validator/branch/develop/graph/badge.svg)](https://codecov.io/gh/typestack/class-validator)
|
5 | [![npm version](https://badge.fury.io/js/class-validator.svg)](https://badge.fury.io/js/class-validator)
|
6 | [![install size](https://packagephobia.now.sh/badge?p=class-validator)](https://packagephobia.now.sh/result?p=class-validator)
|
7 |
|
8 | Allows use of decorator and non-decorator based validation.
|
9 | Internally uses [validator.js][1] to perform validation.
|
10 | Class-validator works on both browser and node.js platforms.
|
11 |
|
12 | ## Table of Contents
|
13 |
|
14 | - [class-validator](#class-validator)
|
15 | - [Table of Contents](#table-of-contents)
|
16 | - [Installation](#installation)
|
17 | - [Usage](#usage)
|
18 | - [Passing options](#passing-options)
|
19 | - [Validation errors](#validation-errors)
|
20 | - [Validation messages](#validation-messages)
|
21 | - [Validating arrays](#validating-arrays)
|
22 | - [Validating sets](#validating-sets)
|
23 | - [Validating maps](#validating-maps)
|
24 | - [Validating nested objects](#validating-nested-objects)
|
25 | - [Validating promises](#validating-promises)
|
26 | - [Inheriting Validation decorators](#inheriting-validation-decorators)
|
27 | - [Conditional validation](#conditional-validation)
|
28 | - [Whitelisting](#whitelisting)
|
29 | - [Passing context to decorators](#passing-context-to-decorators)
|
30 | - [Skipping missing properties](#skipping-missing-properties)
|
31 | - [Validation groups](#validation-groups)
|
32 | - [Custom validation classes](#custom-validation-classes)
|
33 | - [Custom validation decorators](#custom-validation-decorators)
|
34 | - [Using service container](#using-service-container)
|
35 | - [Synchronous validation](#synchronous-validation)
|
36 | - [Manual validation](#manual-validation)
|
37 | - [Validation decorators](#validation-decorators)
|
38 | - [Defining validation schema without decorators](#defining-validation-schema-without-decorators)
|
39 | - [Validating plain objects](#validating-plain-objects)
|
40 | - [Samples](#samples)
|
41 | - [Extensions](#extensions)
|
42 | - [Release notes](#release-notes)
|
43 | - [Contributing](#contributing)
|
44 |
|
45 | ## Installation
|
46 |
|
47 | ```
|
48 | npm install class-validator --save
|
49 | ```
|
50 |
|
51 | > 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.
|
52 |
|
53 | ## Usage
|
54 |
|
55 | Create your class and put some validation decorators on the properties you want to validate:
|
56 |
|
57 | ```typescript
|
58 | import {
|
59 | validate,
|
60 | validateOrReject,
|
61 | Contains,
|
62 | IsInt,
|
63 | Length,
|
64 | IsEmail,
|
65 | IsFQDN,
|
66 | IsDate,
|
67 | Min,
|
68 | Max,
|
69 | } from 'class-validator';
|
70 |
|
71 | export class Post {
|
72 | @Length(10, 20)
|
73 | title: string;
|
74 |
|
75 | @Contains('hello')
|
76 | text: string;
|
77 |
|
78 | @IsInt()
|
79 | @Min(0)
|
80 | @Max(10)
|
81 | rating: number;
|
82 |
|
83 | @IsEmail()
|
84 | email: string;
|
85 |
|
86 | @IsFQDN()
|
87 | site: string;
|
88 |
|
89 | @IsDate()
|
90 | createDate: Date;
|
91 | }
|
92 |
|
93 | let post = new Post();
|
94 | post.title = 'Hello'; // should not pass
|
95 | post.text = 'this is a great post about hell world'; // should not pass
|
96 | post.rating = 11; // should not pass
|
97 | post.email = 'google.com'; // should not pass
|
98 | post.site = 'googlecom'; // should not pass
|
99 |
|
100 | validate(post).then(errors => {
|
101 | // errors is an array of validation errors
|
102 | if (errors.length > 0) {
|
103 | console.log('validation failed. errors: ', errors);
|
104 | } else {
|
105 | console.log('validation succeed');
|
106 | }
|
107 | });
|
108 |
|
109 | validateOrReject(post).catch(errors => {
|
110 | console.log('Promise rejected (validation failed). Errors: ', errors);
|
111 | });
|
112 | // or
|
113 | async function validateOrRejectExample(input) {
|
114 | try {
|
115 | await validateOrReject(input);
|
116 | } catch (errors) {
|
117 | console.log('Caught promise rejection (validation failed). Errors: ', errors);
|
118 | }
|
119 | }
|
120 | ```
|
121 |
|
122 | ### Passing options
|
123 |
|
124 | The `validate` function optionally expects a `ValidatorOptions` object as a second parameter:
|
125 |
|
126 | ```ts
|
127 | export interface ValidatorOptions {
|
128 | skipMissingProperties?: boolean;
|
129 | whitelist?: boolean;
|
130 | forbidNonWhitelisted?: boolean;
|
131 | groups?: string[];
|
132 | dismissDefaultMessages?: boolean;
|
133 | validationError?: {
|
134 | target?: boolean;
|
135 | value?: boolean;
|
136 | };
|
137 |
|
138 | forbidUnknownValues?: boolean;
|
139 | stopAtFirstError?: boolean;
|
140 | }
|
141 | ```
|
142 |
|
143 | > **IMPORTANT**
|
144 | > The `forbidUnknownValues` value is set to `true` by default and **it is highly advised to keep the default**.
|
145 | > Setting it to `false` will result unknown objects passing the validation!
|
146 |
|
147 | ## Validation errors
|
148 |
|
149 | The `validate` method returns an array of `ValidationError` objects. Each `ValidationError` is:
|
150 |
|
151 | ```typescript
|
152 | {
|
153 | target: Object; // Object that was validated.
|
154 | property: string; // Object's property that haven't pass validation.
|
155 | value: any; // Value that haven't pass a validation.
|
156 | constraints?: { // Constraints that failed validation with error messages.
|
157 | [type: string]: string;
|
158 | };
|
159 | children?: ValidationError[]; // Contains all nested validation errors of the property
|
160 | }
|
161 | ```
|
162 |
|
163 | In our case, when we validated a Post object, we have such an array of `ValidationError` objects:
|
164 |
|
165 | ```typescript
|
166 | [{
|
167 | target: /* post object */,
|
168 | property: "title",
|
169 | value: "Hello",
|
170 | constraints: {
|
171 | length: "$property must be longer than or equal to 10 characters"
|
172 | }
|
173 | }, {
|
174 | target: /* post object */,
|
175 | property: "text",
|
176 | value: "this is a great post about hell world",
|
177 | constraints: {
|
178 | contains: "text must contain a hello string"
|
179 | }
|
180 | },
|
181 | // and other errors
|
182 | ]
|
183 | ```
|
184 |
|
185 | If you don't want a `target` to be exposed in validation errors, there is a special option when you use validator:
|
186 |
|
187 | ```typescript
|
188 | validator.validate(post, { validationError: { target: false } });
|
189 | ```
|
190 |
|
191 | This is especially useful when you send errors back over http, and you most probably don't want to expose
|
192 | the whole target object.
|
193 |
|
194 | ## Validation messages
|
195 |
|
196 | You can specify validation message in the decorator options and that message will be returned in the `ValidationError`
|
197 | returned by the `validate` method (in the case that validation for this field fails).
|
198 |
|
199 | ```typescript
|
200 | import { MinLength, MaxLength } from 'class-validator';
|
201 |
|
202 | export class Post {
|
203 | @MinLength(10, {
|
204 | message: 'Title is too short',
|
205 | })
|
206 | @MaxLength(50, {
|
207 | message: 'Title is too long',
|
208 | })
|
209 | title: string;
|
210 | }
|
211 | ```
|
212 |
|
213 | There are few special tokens you can use in your messages:
|
214 |
|
215 | - `$value` - the value that is being validated
|
216 | - `$property` - name of the object's property being validated
|
217 | - `$target` - name of the object's class being validated
|
218 | - `$constraint1`, `$constraint2`, ... `$constraintN` - constraints defined by specific validation type
|
219 |
|
220 | Example of usage:
|
221 |
|
222 | ```typescript
|
223 | import { MinLength, MaxLength } from 'class-validator';
|
224 |
|
225 | export class Post {
|
226 | @MinLength(10, {
|
227 | // here, $constraint1 will be replaced with "10", and $value with actual supplied value
|
228 | message: 'Title is too short. Minimal length is $constraint1 characters, but actual is $value',
|
229 | })
|
230 | @MaxLength(50, {
|
231 | // here, $constraint1 will be replaced with "50", and $value with actual supplied value
|
232 | message: 'Title is too long. Maximal length is $constraint1 characters, but actual is $value',
|
233 | })
|
234 | title: string;
|
235 | }
|
236 | ```
|
237 |
|
238 | Also you can provide a function, that returns a message. This allows you to create more granular messages:
|
239 |
|
240 | ```typescript
|
241 | import { MinLength, MaxLength, ValidationArguments } from 'class-validator';
|
242 |
|
243 | export class Post {
|
244 | @MinLength(10, {
|
245 | message: (args: ValidationArguments) => {
|
246 | if (args.value.length === 1) {
|
247 | return 'Too short, minimum length is 1 character';
|
248 | } else {
|
249 | return 'Too short, minimum length is ' + args.constraints[0] + ' characters';
|
250 | }
|
251 | },
|
252 | })
|
253 | title: string;
|
254 | }
|
255 | ```
|
256 |
|
257 | Message function accepts `ValidationArguments` which contains the following information:
|
258 |
|
259 | - `value` - the value that is being validated
|
260 | - `constraints` - array of constraints defined by specific validation type
|
261 | - `targetName` - name of the object's class being validated
|
262 | - `object` - object that is being validated
|
263 | - `property` - name of the object's property being validated
|
264 |
|
265 | ## Validating arrays
|
266 |
|
267 | If your field is an array and you want to perform validation of each item in the array you must specify a
|
268 | special `each: true` decorator option:
|
269 |
|
270 | ```typescript
|
271 | import { MinLength, MaxLength } from 'class-validator';
|
272 |
|
273 | export class Post {
|
274 | @MaxLength(20, {
|
275 | each: true,
|
276 | })
|
277 | tags: string[];
|
278 | }
|
279 | ```
|
280 |
|
281 | This will validate each item in `post.tags` array.
|
282 |
|
283 | ## Validating sets
|
284 |
|
285 | If your field is a set and you want to perform validation of each item in the set you must specify a
|
286 | special `each: true` decorator option:
|
287 |
|
288 | ```typescript
|
289 | import { MinLength, MaxLength } from 'class-validator';
|
290 |
|
291 | export class Post {
|
292 | @MaxLength(20, {
|
293 | each: true,
|
294 | })
|
295 | tags: Set<string>;
|
296 | }
|
297 | ```
|
298 |
|
299 | This will validate each item in `post.tags` set.
|
300 |
|
301 | ## Validating maps
|
302 |
|
303 | If your field is a map and you want to perform validation of each item in the map you must specify a
|
304 | special `each: true` decorator option:
|
305 |
|
306 | ```typescript
|
307 | import { MinLength, MaxLength } from 'class-validator';
|
308 |
|
309 | export class Post {
|
310 | @MaxLength(20, {
|
311 | each: true,
|
312 | })
|
313 | tags: Map<string, string>;
|
314 | }
|
315 | ```
|
316 |
|
317 | This will validate each item in `post.tags` map.
|
318 |
|
319 | ## Validating nested objects
|
320 |
|
321 | If your object contains nested objects and you want the validator to perform their validation too, then you need to
|
322 | use the `@ValidateNested()` decorator:
|
323 |
|
324 | ```typescript
|
325 | import { ValidateNested } from 'class-validator';
|
326 |
|
327 | export class Post {
|
328 | @ValidateNested()
|
329 | user: User;
|
330 | }
|
331 | ```
|
332 |
|
333 | 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](#validating-plain-objects).
|
334 |
|
335 | It also works with multi-dimensional array, like :
|
336 |
|
337 | ```typescript
|
338 | import { ValidateNested } from 'class-validator';
|
339 |
|
340 | export class Plan2D {
|
341 | @ValidateNested()
|
342 | matrix: Point[][];
|
343 | }
|
344 | ```
|
345 |
|
346 | ## Validating promises
|
347 |
|
348 | If your object contains property with `Promise`-returned value that should be validated, then you need to use the `@ValidatePromise()` decorator:
|
349 |
|
350 | ```typescript
|
351 | import { ValidatePromise, Min } from 'class-validator';
|
352 |
|
353 | export class Post {
|
354 | @Min(0)
|
355 | @ValidatePromise()
|
356 | userId: Promise<number>;
|
357 | }
|
358 | ```
|
359 |
|
360 | It also works great with `@ValidateNested` decorator:
|
361 |
|
362 | ```typescript
|
363 | import { ValidateNested, ValidatePromise } from 'class-validator';
|
364 |
|
365 | export class Post {
|
366 | @ValidateNested()
|
367 | @ValidatePromise()
|
368 | user: Promise<User>;
|
369 | }
|
370 | ```
|
371 |
|
372 | ## Inheriting Validation decorators
|
373 |
|
374 | 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 from both its own class and the base class.
|
375 |
|
376 | ```typescript
|
377 | import { validate } from 'class-validator';
|
378 |
|
379 | class BaseContent {
|
380 | @IsEmail()
|
381 | email: string;
|
382 |
|
383 | @IsString()
|
384 | password: string;
|
385 | }
|
386 |
|
387 | class User extends BaseContent {
|
388 | @MinLength(10)
|
389 | @MaxLength(20)
|
390 | name: string;
|
391 |
|
392 | @Contains('hello')
|
393 | welcome: string;
|
394 |
|
395 | @MinLength(20)
|
396 | password: string;
|
397 | }
|
398 |
|
399 | let user = new User();
|
400 |
|
401 | user.email = 'invalid email'; // inherited property
|
402 | user.password = 'too short'; // password wil be validated not only against IsString, but against MinLength as well
|
403 | user.name = 'not valid';
|
404 | user.welcome = 'helo';
|
405 |
|
406 | validate(user).then(errors => {
|
407 | // ...
|
408 | }); // it will return errors for email, title and text properties
|
409 | ```
|
410 |
|
411 | ## Conditional validation
|
412 |
|
413 | 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`.
|
414 |
|
415 | ```typescript
|
416 | import { ValidateIf, IsNotEmpty } from 'class-validator';
|
417 |
|
418 | export class Post {
|
419 | otherProperty: string;
|
420 |
|
421 | @ValidateIf(o => o.otherProperty === 'value')
|
422 | @IsNotEmpty()
|
423 | example: string;
|
424 | }
|
425 | ```
|
426 |
|
427 | In the example above, the validation rules applied to `example` won't be run unless the object's `otherProperty` is `"value"`.
|
428 |
|
429 | Note that when the condition is false all validation decorators are ignored, including `isDefined`.
|
430 |
|
431 | ## Whitelisting
|
432 |
|
433 | Even if your object is an instance of a validation class it can contain additional properties that are not defined.
|
434 | If you do not want to have such properties on your object, pass special flag to `validate` method:
|
435 |
|
436 | ```typescript
|
437 | import { validate } from 'class-validator';
|
438 | // ...
|
439 | validate(post, { whitelist: true });
|
440 | ```
|
441 |
|
442 | This will strip all properties that don't have any decorators. If no other decorator is suitable for your property,
|
443 | you can use @Allow decorator:
|
444 |
|
445 | ```typescript
|
446 | import {validate, Allow, Min} from "class-validator";
|
447 |
|
448 | export class Post {
|
449 |
|
450 | @Allow()
|
451 | title: string;
|
452 |
|
453 | @Min(0)
|
454 | views: number;
|
455 |
|
456 | nonWhitelistedProperty: number;
|
457 | }
|
458 |
|
459 | let post = new Post();
|
460 | post.title = 'Hello world!';
|
461 | post.views = 420;
|
462 |
|
463 | post.nonWhitelistedProperty = 69;
|
464 | (post as any).anotherNonWhitelistedProperty = "something";
|
465 |
|
466 | validate(post).then(errors => {
|
467 | // post.nonWhitelistedProperty is not defined
|
468 | // (post as any).anotherNonWhitelistedProperty is not defined
|
469 | ...
|
470 | });
|
471 | ```
|
472 |
|
473 | If you would rather to have an error thrown when any non-whitelisted properties are present, pass another flag to
|
474 | `validate` method:
|
475 |
|
476 | ```typescript
|
477 | import { validate } from 'class-validator';
|
478 | // ...
|
479 | validate(post, { whitelist: true, forbidNonWhitelisted: true });
|
480 | ```
|
481 |
|
482 | ## Passing context to decorators
|
483 |
|
484 | It's possible to pass a custom object to decorators which will be accessible on the `ValidationError` instance of the property if validation failed.
|
485 |
|
486 | ```ts
|
487 | import { validate } from 'class-validator';
|
488 |
|
489 | class MyClass {
|
490 | @MinLength(32, {
|
491 | message: 'EIC code must be at least 32 characters',
|
492 | context: {
|
493 | errorCode: 1003,
|
494 | developerNote: 'The validated string must contain 32 or more characters.',
|
495 | },
|
496 | })
|
497 | eicCode: string;
|
498 | }
|
499 |
|
500 | const model = new MyClass();
|
501 |
|
502 | validate(model).then(errors => {
|
503 | //errors[0].contexts['minLength'].errorCode === 1003
|
504 | });
|
505 | ```
|
506 |
|
507 | ## Skipping missing properties
|
508 |
|
509 | Sometimes you may want to skip validation of the properties that do not exist in the validating object. This is
|
510 | usually desirable when you want to update some parts of the object, and want to validate only updated parts,
|
511 | but skip everything else, e.g. skip missing properties.
|
512 | In such situations you will need to pass a special flag to `validate` method:
|
513 |
|
514 | ```typescript
|
515 | import { validate } from 'class-validator';
|
516 | // ...
|
517 | validate(post, { skipMissingProperties: true });
|
518 | ```
|
519 |
|
520 | When skipping missing properties, sometimes you want not to skip all missing properties, some of them maybe required
|
521 | for you, even if skipMissingProperties is set to true. For such cases you should use `@IsDefined()` decorator.
|
522 | `@IsDefined()` is the only decorator that ignores `skipMissingProperties` option.
|
523 |
|
524 | ## Validation groups
|
525 |
|
526 | In different situations you may want to use different validation schemas of the same object.
|
527 | In such cases you can use validation groups.
|
528 |
|
529 | > **IMPORTANT**
|
530 | > Calling a validation with a group combination that would not result in a validation (eg: non existent group name)
|
531 | > will result in a unknown value error. When validating with groups the provided group combination should match at least one decorator.
|
532 |
|
533 | ```typescript
|
534 | import { validate, Min, Length } from 'class-validator';
|
535 |
|
536 | export class User {
|
537 | @Min(12, {
|
538 | groups: ['registration'],
|
539 | })
|
540 | age: number;
|
541 |
|
542 | @Length(2, 20, {
|
543 | groups: ['registration', 'admin'],
|
544 | })
|
545 | name: string;
|
546 | }
|
547 |
|
548 | let user = new User();
|
549 | user.age = 10;
|
550 | user.name = 'Alex';
|
551 |
|
552 | validate(user, {
|
553 | groups: ['registration'],
|
554 | }); // this will not pass validation
|
555 |
|
556 | validate(user, {
|
557 | groups: ['admin'],
|
558 | }); // this will pass validation
|
559 |
|
560 | validate(user, {
|
561 | groups: ['registration', 'admin'],
|
562 | }); // this will not pass validation
|
563 |
|
564 | validate(user, {
|
565 | groups: undefined, // the default
|
566 | }); // this will not pass validation since all properties get validated regardless of their groups
|
567 |
|
568 | validate(user, {
|
569 | groups: [],
|
570 | }); // this will not pass validation, (equivalent to 'groups: undefined', see above)
|
571 | ```
|
572 |
|
573 | There is also a special flag `always: true` in validation options that you can use. This flag says that this validation
|
574 | must be applied always no matter which group is used.
|
575 |
|
576 | ## Custom validation classes
|
577 |
|
578 | If you have custom validation logic you can create a _Constraint class_:
|
579 |
|
580 | 1. First create a file, lets say `CustomTextLength.ts`, and define a new class:
|
581 |
|
582 | ```typescript
|
583 | import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';
|
584 |
|
585 | @ValidatorConstraint({ name: 'customText', async: false })
|
586 | export class CustomTextLength implements ValidatorConstraintInterface {
|
587 | validate(text: string, args: ValidationArguments) {
|
588 | return text.length > 1 && text.length < 10; // for async validations you must return a Promise<boolean> here
|
589 | }
|
590 |
|
591 | defaultMessage(args: ValidationArguments) {
|
592 | // here you can provide default error message if validation failed
|
593 | return 'Text ($value) is too short or too long!';
|
594 | }
|
595 | }
|
596 | ```
|
597 |
|
598 | We marked our class with `@ValidatorConstraint` decorator.
|
599 | You can also supply a validation constraint name - this name will be used as "error type" in ValidationError.
|
600 | If you will not supply a constraint name - it will be auto-generated.
|
601 |
|
602 | Our class must implement `ValidatorConstraintInterface` interface and its `validate` method,
|
603 | which defines validation logic. If validation succeeds, method returns true, otherwise false.
|
604 | Custom validator can be asynchronous, if you want to perform validation after some asynchronous
|
605 | operations, simply return a promise with boolean inside in `validate` method.
|
606 |
|
607 | Also we defined optional method `defaultMessage` which defines a default error message,
|
608 | in the case that the decorator's implementation doesn't set an error message.
|
609 |
|
610 | 2) Then you can use your new validation constraint in your class:
|
611 |
|
612 | ```typescript
|
613 | import { Validate } from 'class-validator';
|
614 | import { CustomTextLength } from './CustomTextLength';
|
615 |
|
616 | export class Post {
|
617 | @Validate(CustomTextLength, {
|
618 | message: 'Title is too short or long!',
|
619 | })
|
620 | title: string;
|
621 | }
|
622 | ```
|
623 |
|
624 | Here we set our newly created `CustomTextLength` validation constraint for `Post.title`.
|
625 |
|
626 | 3) And use validator as usual:
|
627 |
|
628 | ```typescript
|
629 | import { validate } from 'class-validator';
|
630 |
|
631 | validate(post).then(errors => {
|
632 | // ...
|
633 | });
|
634 | ```
|
635 |
|
636 | You can also pass constraints to your validator, like this:
|
637 |
|
638 | ```typescript
|
639 | import { Validate } from 'class-validator';
|
640 | import { CustomTextLength } from './CustomTextLength';
|
641 |
|
642 | export class Post {
|
643 | @Validate(CustomTextLength, [3, 20], {
|
644 | message: 'Wrong post title',
|
645 | })
|
646 | title: string;
|
647 | }
|
648 | ```
|
649 |
|
650 | And use them from `validationArguments` object:
|
651 |
|
652 | ```typescript
|
653 | import { ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';
|
654 |
|
655 | @ValidatorConstraint()
|
656 | export class CustomTextLength implements ValidatorConstraintInterface {
|
657 | validate(text: string, validationArguments: ValidationArguments) {
|
658 | return text.length > validationArguments.constraints[0] && text.length < validationArguments.constraints[1];
|
659 | }
|
660 | }
|
661 | ```
|
662 |
|
663 | ## Custom validation decorators
|
664 |
|
665 | You can also create a custom decorators. Its the most elegant way of using a custom validations.
|
666 | Lets create a decorator called `@IsLongerThan`:
|
667 |
|
668 | 1. Create a decorator itself:
|
669 |
|
670 | ```typescript
|
671 | import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';
|
672 |
|
673 | export function IsLongerThan(property: string, validationOptions?: ValidationOptions) {
|
674 | return function (object: Object, propertyName: string) {
|
675 | registerDecorator({
|
676 | name: 'isLongerThan',
|
677 | target: object.constructor,
|
678 | propertyName: propertyName,
|
679 | constraints: [property],
|
680 | options: validationOptions,
|
681 | validator: {
|
682 | validate(value: any, args: ValidationArguments) {
|
683 | const [relatedPropertyName] = args.constraints;
|
684 | const relatedValue = (args.object as any)[relatedPropertyName];
|
685 | return typeof value === 'string' && typeof relatedValue === 'string' && value.length > relatedValue.length; // you can return a Promise<boolean> here as well, if you want to make async validation
|
686 | },
|
687 | },
|
688 | });
|
689 | };
|
690 | }
|
691 | ```
|
692 |
|
693 | 2. Put it to use:
|
694 |
|
695 | ```typescript
|
696 | import { IsLongerThan } from './IsLongerThan';
|
697 |
|
698 | export class Post {
|
699 | title: string;
|
700 |
|
701 | @IsLongerThan('title', {
|
702 | /* you can also use additional validation options, like "groups" in your custom validation decorators. "each" is not supported */
|
703 | message: 'Text must be longer than the title',
|
704 | })
|
705 | text: string;
|
706 | }
|
707 | ```
|
708 |
|
709 | In your custom decorators you can also use `ValidationConstraint`.
|
710 | Lets create another custom validation decorator called `IsUserAlreadyExist`:
|
711 |
|
712 | 1. Create a ValidationConstraint and decorator:
|
713 |
|
714 | ```typescript
|
715 | import {
|
716 | registerDecorator,
|
717 | ValidationOptions,
|
718 | ValidatorConstraint,
|
719 | ValidatorConstraintInterface,
|
720 | ValidationArguments,
|
721 | } from 'class-validator';
|
722 |
|
723 | @ValidatorConstraint({ async: true })
|
724 | export class IsUserAlreadyExistConstraint implements ValidatorConstraintInterface {
|
725 | validate(userName: any, args: ValidationArguments) {
|
726 | return UserRepository.findOneByName(userName).then(user => {
|
727 | if (user) return false;
|
728 | return true;
|
729 | });
|
730 | }
|
731 | }
|
732 |
|
733 | export function IsUserAlreadyExist(validationOptions?: ValidationOptions) {
|
734 | return function (object: Object, propertyName: string) {
|
735 | registerDecorator({
|
736 | target: object.constructor,
|
737 | propertyName: propertyName,
|
738 | options: validationOptions,
|
739 | constraints: [],
|
740 | validator: IsUserAlreadyExistConstraint,
|
741 | });
|
742 | };
|
743 | }
|
744 | ```
|
745 |
|
746 | note that we marked our constraint that it will by async by adding `{ async: true }` in validation options.
|
747 |
|
748 | 2. And put it to use:
|
749 |
|
750 | ```typescript
|
751 | import { IsUserAlreadyExist } from './IsUserAlreadyExist';
|
752 |
|
753 | export class User {
|
754 | @IsUserAlreadyExist({
|
755 | message: 'User $value already exists. Choose another name.',
|
756 | })
|
757 | name: string;
|
758 | }
|
759 | ```
|
760 |
|
761 | ## Using service container
|
762 |
|
763 | Validator supports service container in the case if want to inject dependencies into your custom validator constraint
|
764 | classes. Here is example how to integrate it with [typedi][2]:
|
765 |
|
766 | ```typescript
|
767 | import { Container } from 'typedi';
|
768 | import { useContainer, Validator } from 'class-validator';
|
769 |
|
770 | // do this somewhere in the global application level:
|
771 | useContainer(Container);
|
772 | let validator = Container.get(Validator);
|
773 |
|
774 | // now everywhere you can inject Validator class which will go from the container
|
775 | // also you can inject classes using constructor injection into your custom ValidatorConstraint-s
|
776 | ```
|
777 |
|
778 | ## Synchronous validation
|
779 |
|
780 | If you want to perform a simple non async validation you can use `validateSync` method instead of regular `validate`
|
781 | method. It has the same arguments as `validate` method. But note, this method **ignores** all async validations
|
782 | you have.
|
783 |
|
784 | ## Manual validation
|
785 |
|
786 | There are several method exist in the Validator that allows to perform non-decorator based validation:
|
787 |
|
788 | ```typescript
|
789 | import { isEmpty, isBoolean } from 'class-validator';
|
790 |
|
791 | isEmpty(value);
|
792 | isBoolean(value);
|
793 | ```
|
794 |
|
795 | ## Validation decorators
|
796 |
|
797 |
|
798 |
|
799 | | Decorator | Description |
|
800 | | ------------------------------------------------| ----------- |
|
801 | | **Common validation decorators** | |
|
802 | | `@IsDefined(value: any)` | Checks if value is defined (!== undefined, !== null). This is the only decorator that ignores skipMissingProperties option. |
|
803 | | `@IsOptional()` | Checks if given value is empty (=== null, === undefined) and if so, ignores all the validators on the property. |
|
804 | | `@Equals(comparison: any)` | Checks if value equals ("===") comparison. |
|
805 | | `@NotEquals(comparison: any)` | Checks if value not equal ("!==") comparison. |
|
806 | | `@IsEmpty()` | Checks if given value is empty (=== '', === null, === undefined). |
|
807 | | `@IsNotEmpty()` | Checks if given value is not empty (!== '', !== null, !== undefined). |
|
808 | | `@IsIn(values: any[])` | Checks if value is in an array of allowed values. |
|
809 | | `@IsNotIn(values: any[])` | Checks if value is not in an array of disallowed values. |
|
810 | | **Type validation decorators** | |
|
811 | | `@IsBoolean()` | Checks if a value is a boolean. |
|
812 | | `@IsDate()` | Checks if the value is a date. |
|
813 | | `@IsString()` | Checks if the value is a string. |
|
814 | | `@IsNumber(options: IsNumberOptions)` | Checks if the value is a number. |
|
815 | | `@IsInt()` | Checks if the value is an integer number. |
|
816 | | `@IsArray()` | Checks if the value is an array |
|
817 | | `@IsEnum(entity: object)` | Checks if the value is a valid enum |
|
818 | | **Number validation decorators** |
|
819 | | `@IsDivisibleBy(num: number)` | Checks if the value is a number that's divisible by another. |
|
820 | | `@IsPositive()` | Checks if the value is a positive number greater than zero. |
|
821 | | `@IsNegative()` | Checks if the value is a negative number smaller than zero. |
|
822 | | `@Min(min: number)` | Checks if the given number is greater than or equal to given number. |
|
823 | | `@Max(max: number)` | Checks if the given number is less than or equal to given number. |
|
824 | | **Date validation decorators** |
|
825 | | `@MinDate(date: Date | (() => Date))` | Checks if the value is a date that's after the specified date. |
|
826 | | `@MaxDate(date: Date | (() => Date))` | Checks if the value is a date that's before the specified date. |
|
827 | | **String-type validation decorators** | |
|
828 | | `@IsBooleanString()` | Checks if a string is a boolean (e.g. is "true" or "false" or "1", "0"). |
|
829 | | `@IsDateString()` | Alias for `@IsISO8601()`. |
|
830 | | `@IsNumberString(options?: IsNumericOptions)` | Checks if a string is a number. |
|
831 | | **String validation decorators** | |
|
832 | | `@Contains(seed: string)` | Checks if the string contains the seed. |
|
833 | | `@NotContains(seed: string)` | Checks if the string not contains the seed. |
|
834 | | `@IsAlpha()` | Checks if the string contains only letters (a-zA-Z). |
|
835 | | `@IsAlphanumeric()` | Checks if the string contains only letters and numbers. |
|
836 | | `@IsDecimal(options?: IsDecimalOptions)` | Checks if the string is a valid decimal value. Default IsDecimalOptions are `force_decimal=False`, `decimal_digits: '1,'`, `locale: 'en-US'` |
|
837 | | `@IsAscii()` | Checks if the string contains ASCII chars only. |
|
838 | | `@IsBase32()` | Checks if a string is base32 encoded. |
|
839 | | `@IsBase58()` | Checks if a string is base58 encoded. |
|
840 | | `@IsBase64()` | Checks if a string is base64 encoded. |
|
841 | | `@IsIBAN()` | Checks if a string is a IBAN (International Bank Account Number). |
|
842 | | `@IsBIC()` | Checks if a string is a BIC (Bank Identification Code) or SWIFT code. |
|
843 | | `@IsByteLength(min: number, max?: number)` | Checks if the string's length (in bytes) falls in a range. |
|
844 | | `@IsCreditCard()` | Checks if the string is a credit card. |
|
845 | | `@IsCurrency(options?: IsCurrencyOptions)` | Checks if the string is a valid currency amount. |
|
846 | | `@IsISO4217CurrencyCode()` | Checks if the string is an ISO 4217 currency code. |
|
847 | | `@IsEthereumAddress()` | Checks if the string is an Ethereum address using basic regex. Does not validate address checksums. |
|
848 | | `@IsBtcAddress()` | Checks if the string is a valid BTC address. |
|
849 | | `@IsDataURI()` | Checks if the string is a data uri format. |
|
850 | | `@IsEmail(options?: IsEmailOptions)` | Checks if the string is an email.|
|
851 | | `@IsFQDN(options?: IsFQDNOptions)` | Checks if the string is a fully qualified domain name (e.g. domain.com). |
|
852 | | `@IsFullWidth()` | Checks if the string contains any full-width chars. |
|
853 | | `@IsHalfWidth()` | Checks if the string contains any half-width chars. |
|
854 | | `@IsVariableWidth()` | Checks if the string contains a mixture of full and half-width chars. |
|
855 | | `@IsHexColor()` | Checks if the string is a hexadecimal color. |
|
856 | | `@IsHSL()` | Checks if the string is an HSL color based on [CSS Colors Level 4 specification](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). |
|
857 | | `@IsRgbColor(options?: IsRgbOptions)` | Checks if the string is a rgb or rgba color. |
|
858 | | `@IsIdentityCard(locale?: string)` | Checks if the string is a valid identity card code. |
|
859 | | `@IsPassportNumber(countryCode?: string)` | Checks if the string is a valid passport number relative to a specific country code. |
|
860 | | `@IsPostalCode(locale?: string)` | Checks if the string is a postal code. |
|
861 | | `@IsHexadecimal()` | Checks if the string is a hexadecimal number. |
|
862 | | `@IsOctal()` | Checks if the string is a octal number. |
|
863 | | `@IsMACAddress(options?: IsMACAddressOptions)` | Checks if the string is a MAC Address. |
|
864 | | `@IsIP(version?: "4"\|"6")` | Checks if the string is an IP (version 4 or 6). |
|
865 | | `@IsPort()` | Checks if the string is a valid port number. |
|
866 | | `@IsISBN(version?: "10"\|"13")` | Checks if the string is an ISBN (version 10 or 13). |
|
867 | | `@IsEAN()` | Checks if the string is an if the string is an EAN (European Article Number). |
|
868 | | `@IsISIN()` | Checks if the string is an ISIN (stock/security identifier). |
|
869 | | `@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. |
|
870 | | `@IsJSON()` | Checks if the string is valid JSON. |
|
871 | | `@IsJWT()` | Checks if the string is valid JWT. |
|
872 | | `@IsObject()` | Checks if the object is valid Object (null, functions, arrays will return false). |
|
873 | | `@IsNotEmptyObject()` | Checks if the object is not empty. |
|
874 | | `@IsLowercase()` | Checks if the string is lowercase. |
|
875 | | `@IsLatLong()` | Checks if the string is a valid latitude-longitude coordinate in the format lat, long. |
|
876 | | `@IsLatitude()` | Checks if the string or number is a valid latitude coordinate. |
|
877 | | `@IsLongitude()` | Checks if the string or number is a valid longitude coordinate. |
|
878 | | `@IsMobilePhone(locale: string)` | Checks if the string is a mobile phone number. |
|
879 | | `@IsISO31661Alpha2()` | Checks if the string is a valid ISO 3166-1 alpha-2 officially assigned country code. |
|
880 | | `@IsISO31661Alpha3()` | Checks if the string is a valid ISO 3166-1 alpha-3 officially assigned country code. |
|
881 | | `@IsLocale()` | Checks if the string is a locale. |
|
882 | | `@IsPhoneNumber(region: string)` | Checks if the string is a valid phone number using libphonenumber-js. |
|
883 | | `@IsMongoId()` | Checks if the string is a valid hex-encoded representation of a MongoDB ObjectId. |
|
884 | | `@IsMultibyte()` | Checks if the string contains one or more multibyte chars. |
|
885 | | `@IsNumberString(options?: IsNumericOptions)` | Checks if the string is numeric. |
|
886 | | `@IsSurrogatePair()` | Checks if the string contains any surrogate pairs chars. |
|
887 | | `@IsTaxId()` | Checks if the string is a valid tax ID. Default locale is `en-US`.
|
888 | | `@IsUrl(options?: IsURLOptions)` | Checks if the string is a URL. |
|
889 | | `@IsMagnetURI()` | Checks if the string is a [magnet uri format](https://en.wikipedia.org/wiki/Magnet_URI_scheme). |
|
890 | | `@IsUUID(version?: "3"\|"4"\|"5"\|"all")` | Checks if the string is a UUID (version 3, 4, 5 or all ). |
|
891 | | `@IsFirebasePushId()` | Checks if the string is a [Firebase Push ID](https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html) |
|
892 | | `@IsUppercase()` | Checks if the string is uppercase. |
|
893 | | `@Length(min: number, max?: number)` | Checks if the string's length falls in a range. |
|
894 | | `@MinLength(min: number)` | Checks if the string's length is not less than given number. |
|
895 | | `@MaxLength(max: number)` | Checks if the string's length is not more than given number. |
|
896 | | `@Matches(pattern: RegExp, modifiers?: string)` | Checks if string matches the pattern. Either matches('foo', /foo/i) or matches('foo', 'foo', 'i'). |
|
897 | | `@IsMilitaryTime()` | Checks if the string is a valid representation of military time in the format HH:MM. |
|
898 | | `@IsTimeZone()` | Checks if the string represents a valid IANA time-zone. |
|
899 | | `@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`. |
|
900 | | `@IsMimeType()` | Checks if the string matches to a valid [MIME type](https://en.wikipedia.org/wiki/Media_type) format |
|
901 | | `@IsSemVer()` | Checks if the string is a Semantic Versioning Specification (SemVer). |
|
902 | | `@IsISSN(options?: IsISSNOptions)` | Checks if the string is a ISSN. |
|
903 | | `@IsISRC()` | Checks if the string is a [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code). |
|
904 | | `@IsRFC3339()` | Checks if the string is a valid [RFC 3339](https://tools.ietf.org/html/rfc3339) date. |
|
905 | | `@IsStrongPassword(options?: IsStrongPasswordOptions)` | Checks if the string is a strong password. |
|
906 | | **Array validation decorators** | |
|
907 | | `@ArrayContains(values: any[])` | Checks if array contains all values from the given array of values. |
|
908 | | `@ArrayNotContains(values: any[])` | Checks if array does not contain any of the given values. |
|
909 | | `@ArrayNotEmpty()` | Checks if given array is not empty. |
|
910 | | `@ArrayMinSize(min: number)` | Checks if the array's length is greater than or equal to the specified number. |
|
911 | | `@ArrayMaxSize(max: number)` | Checks if the array's length is less or equal to the specified number. |
|
912 | | `@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. |
|
913 | | **Object validation decorators** |
|
914 | | `@IsInstance(value: any)` | Checks if the property is an instance of the passed value. |
|
915 | | **Other decorators** | |
|
916 | | `@Allow()` | Prevent stripping off the property when no other constraint is specified for it. |
|
917 |
|
918 | ## Defining validation schema without decorators
|
919 |
|
920 | Schema-based validation without decorators is no longer supported by `class-validator`. This feature was broken in version 0.12 and it will not be fixed. If you are interested in schema-based validation, you can find several such frameworks in [the zod readme's comparison section](https://github.com/colinhacks/zod#comparison).
|
921 |
|
922 | ## Validating plain objects
|
923 |
|
924 | Due to nature of the decorators, the validated object has to be instantiated using `new Class()` syntax. If you have your class defined using class-validator decorators and you want to validate plain JS object (literal object or returned by JSON.parse), you need to transform it to the class instance via using [class-transformer](https://github.com/pleerock/class-transformer)).
|
925 |
|
926 | ## Samples
|
927 |
|
928 | Take a look on samples in [./sample](https://github.com/pleerock/class-validator/tree/master/sample) for more examples of
|
929 | usages.
|
930 |
|
931 | ## Extensions
|
932 |
|
933 | There are several extensions that simplify class-validator integration with other modules:
|
934 |
|
935 | - [class-validator integration](https://github.com/19majkel94/class-transformer-validator) with [class-transformer](https://github.com/pleerock/class-transformer)
|
936 | - [class-validator-rule](https://github.com/yantrab/class-validator-rule)
|
937 | - [ngx-dynamic-form-builder](https://github.com/EndyKaufman/ngx-dynamic-form-builder)
|
938 | - [abarghoud/ngx-reactive-form-class-validator](https://github.com/abarghoud/ngx-reactive-form-class-validator)
|
939 |
|
940 | ## Release notes
|
941 |
|
942 | See information about breaking changes and release notes [here][3].
|
943 |
|
944 | [1]: https://github.com/chriso/validator.js
|
945 | [2]: https://github.com/pleerock/typedi
|
946 | [3]: CHANGELOG.md
|
947 |
|
948 | ## Contributing
|
949 |
|
950 | For information about how to contribute to this project, see [TypeStack's general contribution guide](https://github.com/typestack/.github/blob/master/CONTRIBUTING.md).
|