Hello everyone, I’m new in the forum. This is the first time I have used custom validators. Basically I want to check if the username is already in use and if so the Update Profile button is not enabled. But it doesn’t work, if I try to enter in the form a username that already exists in the Real time database of firebase the button is enabled, but in the console I get the message “username già in uso”. Am I doing something wrong with the UsernameValidator class?
import { FormControl } from '@angular/forms';
import * as firebase from 'firebase';
export class UsernameValidator {
static validUsername(fc: FormControl){
firebase.database().ref().child("users").orderByChild("username")
.equalTo(fc.value)
.once("value",snapshot => {
if (snapshot.exists()){
console.log("username già in uso")
return ({validUsername: false});
}
else
return (null);
});
}
}
This is where I define the form group and validators:
constructor(private route: ActivatedRoute, private router: Router,
public pfService: ProfileService, public fb: FormBuilder,
public authService: AuthenticationService)
{
this.id = this.authService.userData.uid;
//Underscore and dot can't be next to each other (e.g user_.name).
//Underscore or dot can't be used multiple times in a row (e.g user__name / user..name).
this.validPattern = "^(?=.{6,20}$)(?!.*[_.]{2})[a-z0-9._]+$";
this.validPatternName = "^[a-z]{3,10}$";
this.userForm = fb.group({
txtUsername: ["",[Validators.required,Validators.pattern(this.validPattern),
UsernameValidator.validUsername]],
txtName: ["",[Validators.required,Validators.pattern(this.validPatternName)]],
});
this.userForm .valueChanges.subscribe(()=> {
console.log(this.userForm.getError('validUsername'))
})
};
This is the HTML code:
<ion-content>
<ion-list lines="full">
<form [formGroup]="userForm" (ngSubmit)="updateForm()" >
<ion-item>
<ion-label class="form-control" position="floating">Userame</ion-label>
<ion-input formControlName="txtUsername" type="text" ></ion-input>
<span [hidden]="userForm.controls.txtUsername.valid || userForm.controls.txtUsername.pristine">Lunghezza tra 6 e 20 caratteri</span>
</ion-item>
<ion-item>
<ion-label class="form-control" position="floating">Name</ion-label>
<ion-input formControlName="txtName" type="text" > </ion-input>
<span [hidden]="userForm.controls.txtName.valid || userForm.controls.txtName.pristine">Lunghezza tra 6 e 20 caratteri</span>
<p *ngIf="userForm.get('txtUsername').hasError('validUsername')" color="danger">Username GIà IN USO</p>
</ion-item>
<ion-row>
<ion-col>
<ion-button type="submit" *ngIf="userForm.controls.txtUsername.valid && userForm.controls.txtName.valid " color="primary" shape="full" expand="block">Update Profile</ion-button>
</ion-col>
</ion-row>
</form>
</ion-list>
</ion-content>
The validator won’t return anything as it going to get stucked inside the snapshot. It return always null. How can I modify the code?