Currently, I am in the process of following a tutorial to implement Asynchronous validation in Angular. The goal is to create a custom validator named shouldBeUnique
that will be triggered after a 2-second delay. To achieve this, I have utilized the setTimeout
function within the validator. However, I am facing an issue where the error message is not being displayed in the designated div.
Below is my custom validation error file:
import { AbstractControl, ValidationErrors } from '@angular/forms';
export class UsernameValidator {
static cannotContainSpace(control: AbstractControl): ValidationErrors | null {
if ((control.value as string).indexOf(' ') >= 0) {
return { cannotContainSpace: true };
}
return null;
}
static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value === 'bilal') {
resolve({shouldBeUnique: true});
} else {
resolve(null);
}
}, 2000);
});
}
}
Here is the HTML file snippet:
<form [formGroup] = "form">
<div class="form-group">
<label for="username">Username</label>
<input
formControlName = "username"
id="username"
type="text"
class="form-control">
<div *ngIf="username.touched && username.invalid" class="alert alert-danger">
<div *ngIf="username.errors.required">Username is required</div>
<div *ngIf="username.errors.minlength">
Minimum length of {{username.errors.minlength.requiredLength}} characters is required
</div>
<div *ngIf="username.errors.cannotContainSpace">
Username cannot contain spaces
</div>
<div *ngIf="username.errors.shouldBeUnique">
Username must be unique
</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
formControlName = "password"
id="password"
type="text"
class="form-control">
</div>
<button class="btn btn-primary" type="submit">Sign Up</button>
</form>
Lastly, here is the TypeScript file:
import { Component } from '@angular/core';
import {FormGroup, FormControl, Validators} from '@angular/forms';
import { UsernameValidator } from './username.validator';
@Component({
// tslint:disable-next-line:component-selector
selector: 'signup-form',
templateUrl: './signup-form.component.html',
styleUrls: ['./signup-form.component.css']
})
export class SignupFormComponent {
form = new FormGroup({
username: new FormControl('', [
Validators.required,
Validators.minLength(3),
UsernameValidator.cannotContainSpace,
UsernameValidator.shouldBeUnique
]),
password: new FormControl('' , Validators.required)
});
get username() {
return this.form.get('username');
}
}