Search code examples
angularformsangular-validation

How to add composeAsync to angular 5 validators


I'm working on an Angular 5 forms module using reactive forms approach. In that form for one of my form controls, I need some back-end validation to be done, Can someone help to implement composeAsync function handle back-end validations?


Solution

  • Here is how I implemented (for username check)

    First I have added a report validation function for remort validation

    this.regForm = this.fb.group({
          userName: ['', Validators.required, 
                     this.validateUserIDNotTaken.bind(this) ],
          password: [ '', [Validators.required]]
    });
    

    then

    validateUserIDNotTaken(control: AbstractControl) {
        return this.userService.validateUserIDNotTaken(control.value).map(res => {
          return res ? null : { unTaken: true };
        });
    }
    

    in user service

    export class validateUserIDNotTaken{
      static createValidator(userService: UserService) {
        return (control: AbstractControl) => {
          return userService.validateUserIDNotTaken(control.value).map(res => {
            return res ? null : { unTaken: true };
          });
        };
      }
    }
    

    and added this to the template

    <div *ngIf="regForm.get('userName').errors && regForm .get('userName').errors.unTaken">
       This userName is already taken!
    </div>