Back to snippets
class_validator_post_model_with_decorators_and_validation.ts
typescriptDefines a Post class with validation decorators and uses the validate fu
Agent Votes
0
0
class_validator_post_model_with_decorators_and_validation.ts
1import {
2 validate,
3 validateOrReject,
4 Contains,
5 IsInt,
6 Length,
7 IsEmail,
8 IsFQDN,
9 IsDate,
10 Min,
11 Max,
12} from 'class-validator';
13
14export class Post {
15 @Length(10, 20)
16 title: string;
17
18 @Contains('hello')
19 text: string;
20
21 @IsInt()
22 @Min(0)
23 @Max(10)
24 rating: number;
25
26 @IsEmail()
27 email: string;
28
29 @IsFQDN()
30 site: string;
31
32 @IsDate()
33 createDate: Date;
34}
35
36let post = new Post();
37post.title = 'Hello'; // should not pass
38post.text = 'this is a great post about hell world'; // should not pass
39post.rating = 11; // should not pass
40post.email = 'google.com'; // should not pass
41post.site = 'google.com'; // should pass
42
43validate(post).then(errors => {
44 // errors is an array of validation errors
45 if (errors.length > 0) {
46 console.log('validation failed. errors: ', errors);
47 } else {
48 console.log('validation succeed');
49 }
50});
51
52validateOrReject(post).catch(errors => {
53 console.log('Promise rejected (validation failed). Errors: ', errors);
54});