Hi, i created a form field with ionic but wants the username field to be unique. Therefore, it has to check whether the username input is in the firebase realtime database or not.
If it is in the database it should not allow you to register. But it will instead prompt you to enter a different username.
Am trying to do it using the following, but its not working:
this is the ts. file
export class RegisterPage {
registerForm: FormGroup;
constructor(private afs: AngularFirestore, private fb: FormBuilder) { }
ngOnInit() {
this.loginForm = this.fb.group({
email: ['', [
Validators.required,
Validators.email,
]],
username: ['',
Validators.required,
CustomValidator.username(this.afs)
],
});
}
// Use getters for cleaner HTML code
get email() {
return this.loginForm.get('email')
}
get name() {
return this.loginForm.get('name')
}
}
export class CustomValidator {
static username(afs: AngularFirestore) {
return (control: AbstractControl) => {
// return an observable here....
const username = control.value.toLowerCase();
return afs.collection('person-list', ref => ref.where('username', '==', username) )
.valueChanges().pipe(
debounceTime(500),
take(1),
map(arr => arr.length ? {nameAvailable: false } : null ),
)
}
}
}
.html file
<form [formGroup]="loginForm" novalidate>
<ion-item >
<ion-label for="email">Email</ion-label><br>
<ion-input type="email" formControlName="email"></ion-input>
</ion-item>
<div class="alert alert-danger" *ngIf="email.touched && email.invalid">
<div *ngIf="email.errors.asyncUnique" class="notification is-danger">
{{ email.value }} email must be unique
</div>
</div>
<ion-item >
<ion-label for="username">Name</ion-label><br>
<ion-input type="username" formControlName="username"></ion-input>
</ion-item>
<div *ngIf="username .invalid && username.dirty" class="notification is-danger">
{{ username.value }} is already taken
</div>
<div *ngIf="username .valid" class="notification is-success">
{{ username.value }} is available
</div>
<div *ngIf="username .pending" class="notification is-info">
Hold tight... Checking availability of {{ username.value }}
</div>
<button [disabled]="!loginForm.valid"> Button</button>
</form>
Will really appreciate your help.
Thanks you in advance.