0
votes

I am having an issue with this custom form validator

Here is my form builder:

buildForm(): void {

    this.step1Form = this.fb.group({
        username: new FormControl('', {
                validators: [Validators.required,
                Validators.minLength(4)],
        }),
        email: new FormControl('', {
                validators: [Validators.required,
                Validators.pattern("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")],
        }),
        password: new FormControl('', {
                validators: [Validators.required,
                Validators.minLength(8)],
        }),
        repeat: new FormControl('', {
                validators: [Validators.required,
                Validators.minLength(8)],
        }),
        }, { validator: this.checkUsername.bind(this)});

    this.activeForm = this.step1Form;

}

and here is the checkUsername method

checkUsername(g: FormGroup) {
    this.dataService.checkUsername(g.get('username').value).subscribe(data => {
            return typeof data["error"] != 'undefined' ? null : {'taken': true};
    });
}

I can see my method is being called when I type into the username field and it returns {"error":true,"0":"User not found!"} when username is not found, and returns json data of the user if it is found.

My problem is I have this next button and is suppose to be disabled when the form is not valid, but when I type in a username I know is already taken the button is not disabled:

<div [ngClass]="{'text-right': tabActive != 5}">
    <button [ngClass]="{'mr-30': tabActive != 5}"
    [disabled]="!activeForm.valid" 
    class="save-btn next-btn" (click)="next()">
    {{ tabActive == 5 ? "Finish" : "Next" }} <i class="fa fa-angle-right"></i>
    </button>
</div>

Here is the actual form. My question is what am I doing wrong? I can see the method is being called and its returning what it should, its not making my form invalid when the username is taken

    <form [formGroup]="step1Form">
    <div class="col-md-4">
            <input type="file" id="profile-image" (change)="selectFile($event)" name="image" accept="image/*" capture style="display:none"/>
            <img src="assets/images/image-upload.png" (click)="profileImgClick($event)" />
    </div>
    <div class="col-md-8">
    <div class="info" *ngIf="errors.taken">
            <i class="fa fa-info-circle"></i>The username is already in use
    </div>
    <div class="form-group">
        <span class="icon"><i class="far fa-user"></i></span>
        <input [(ngModel)]="patient.patient_username" formControlName="username" type="text" maxlength="9" class="form-control control-icon" placeholder="Username">
        <div *ngIf="errors.username" class="error">{{ errors.username }}</div>
    </div>
    <div class="form-group">
        <span class="icon"><i class="fa fa-envelope"></i></span>
        <input [(ngModel)]="patient.email" formControlName="email" type="text" class="form-control control-icon" placeholder="Your email">
        <div *ngIf="errors.email" class="error">{{ errors.email }}</div>
    </div>
    <div class="form-group">
        <span class="icon"><i class="fa fa-key"></i></span>
        <input [(ngModel)]="patient.password" formControlName="password" type="password" class="form-control control-icon" placeholder="Password">
        <div *ngIf="errors.password" class="error">{{ errors.password }}</div>
    </div>
    <div class="form-group">
        <span class="icon"><i class="fa fa-key"></i></span>
        <input formControlName="repeat" type="password" class="form-control control-icon" placeholder="Repeat password">
        <div *ngIf="errors.repeat" class="error">{{ errors.repeat }}</div>
    </div>
    </div>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</form>

Here is dataService.checkUsername

checkUsername(username):Observable<any> {
            return this.http.get(globals.baseUrl+'/user/' + username, {headers:this.utilService.getHeadersJson()}).map(this.utilService.map);
        }
1

1 Answers

0
votes

Return an Observable from the async validator.

checkUsername(g: FormGroup) {
    return this.dataService.checkUsername(g.get('username').value).pipe(map(data => {
        return typeof data["error"] != 'undefined' ? null : {'taken': true};
    }));
}

And I believe the validator should be added to the username control instead? shouldn't it?

username: new FormControl('', 
    {validators: [Validators.required, Validators.minLength(4)],
    asyncValidators: [this.checkUsername.bind(this)]}
),