Cross field validation in Angular2

后端 未结 3 461
情话喂你
情话喂你 2020-12-02 16:29

I\'m building an Angular2 client side application. I\'m currently working on the membership components and integrating client side components with MVC6 vNext Identity v3.

3条回答
  •  情话喂你
    2020-12-02 16:32

    You can also use a custom directive validator to compare the fields.

    In your html:

    Password is required
    Password mismatch

    And your directive:

    import { Directive, forwardRef, Attribute } from '@angular/core';
    import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
    @Directive({
        selector: '[validateEqual][formControlName],[validateEqual][formControl],[validateEqual][ngModel]',
        providers: [
            { provide: NG_VALIDATORS, useExisting: forwardRef(() => EqualValidator), multi: true }
        ]
    })
    export class EqualValidator implements Validator {
        constructor( @Attribute('validateEqual') public validateEqual: string) {}
    
        validate(c: AbstractControl): { [key: string]: any } {
            // self value (e.g. retype password)
            let v = c.value;
    
            // control value (e.g. password)
            let e = c.root.get(this.validateEqual);
    
            // value not equal
            if (e && v !== e.value) return {
                validateEqual: false
            }
            return null;
        }
    }
    

    Here is the complete solution in plunkr:

    https://plnkr.co/edit/KgjSTj7VqbWMnRdYZdxM?p=preview

提交回复
热议问题