简体   繁体   中英

Using decorators for validation in Angular 2 with TypeScript

I am working on a project where I use Angular 2 and NodeJS with TypeScript.

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

Instead of expressing a required field in markup like this:

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

I would like to do this:

class Hero {
    id: number;

    @Required
    name: string;
}

I'm trying to figure out how to go about writing directive to read the metadata in to apply the required attribute to the input element as well as in NodeJS to create validation errors. Any guidance is appreciated. Thank you for your help.

The problem consists of two things: - Validating a Model based on decorators - Showing the result in the UI

For the first thing you can use any typescript validator. Eg Class validator. The second part Im still trying to figure out.

Edit: After looking into it, I would do it like that: Use Class Validator for the decorators, create a form using the angular 2 form builder, attach to the valueChanged event of the form, in the event execute the validator and set for each validation error you receive, the corresponding formcontrol errors. (Look for setErrors method.)

Keep in mind, that any change in the form now reevaluates all inputs. This might need to be improved. Furthermore I would abstract all that logic into a service, that will provide a form based on a typescript class and hooks up all the things needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM