Using decorators to validate in Angular 2 with TypeScript

I am working on a project in which I am using Angular 2 and NodeJS with TypeScript.

Angular2 uses decorators to define Components. I would like to be able to express the validation logic on domain objects in the same way. This would be useful because I could express the validation rule 1 time and use it both on the server side and on the client side.

Instead of expressing the required field in the markup as follows:

<input required [(ng-model)]="selectedHero.name"></input>

I would like to do this:

class Hero {
    id: number;

    @Required
    name: string;
}

I am trying to figure out how to write a directive to read metadata to apply the required attribute to an input element, and also in NodeJS to generate validation errors. Any recommendations are appreciated. Thank you for your help.

+4
1

: - -

typescript. . . Im .

: , : Class Validator , , angular 2, valueChanged , . ( setErrors.)

, . , . , , , typescript, .

+3

Source: https://habr.com/ru/post/1618010/


All Articles