Custom Validator on reactive form for password and confirm password matching getting undefined parameters into Angular 4

后端 未结 9 1368
遥遥无期
遥遥无期 2020-12-01 00:47

I\'m trying to implement a custom validator to check if the password and password confirm are equal. The problem is that the validator is getting undefined password and conf

9条回答
  •  再見小時候
    2020-12-01 01:17

    The issue is that you are mixing the reactive forms module with the input approach. This is causing you to get undefined when passing the values to the validator.

    You don't need to bind to the ng-model when using the reactive forms. Instead, you should access the value of the fields from the Instance of FormGroup.

    I do something like this in an app to validate the passwords match.

    public Credentials: FormGroup;
    
    ngOnInit() {
        this.Credentials = new FormGroup({});
        this.Credentials.addControl('Password', new FormControl('', [Validators.required]));
        this.Credentials.addControl('Confirmation', new FormControl(
            '', [Validators.compose(
                [Validators.required, this.validateAreEqual.bind(this)]
            )]
        ));
    }
    
    private validateAreEqual(fieldControl: FormControl) {
        return fieldControl.value === this.Credentials.get("Password").value ? null : {
            NotEqual: true
        };
    }
    

    Note that the validator expects a FormControl field as a parameter and it compares the value of the field to that of the value of the Password field of the Credentials FormGroup.

    In the HTML make sure to remove the ng-model.

    
    
    
    

    Hope this helps!

提交回复
热议问题