Username already exists, please check for available options during sign up
Solution 1
You can use AsyncValidator and asynchronous-validation-in-angulars
Or my implementation:
Form initialize:
this.form = this.formBuilder.group({
username: [{value: null, disabled: false},
[Validators.required, this.validateUsername()]]
})
Custom validator:
private validateUsername(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
this.someServiceWorkingWithDatabase.checkUsername(control)
.subscribe(
({data}) => {
let res: string = data;
if (res === control.value) {
return {'alreadyExist': true};
} else {
return null
}
},
(error) => {
console.log(error);
}
)
}
}
Template:
<div class="formError" *ngIf="this.form['controls']
.username.hasError('alreadyExist')">
*this username already exists in our database</div>
Solution 2
Now i will create student form with unique emailid using angular, nodejs and mongodb
HTML FILE
<div class="form-group">
<label class="col-md-4">Email</label>
<input type="email" class="form-control" formControlName="s_email" #s_email (change)="emailCheckUnique()" />
</div>
<div *ngIf="angForm.controls['s_email'].invalid && (angForm.controls['s_email'].dirty || angForm.controls['s_email'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['s_email'].errors.required">
E-mail is required.
</div>
<div *ngIf="angForm.controls['s_email'].errors.email">
Enter Valid E-mail
</div>
</div>
<div *ngIf="emailAlredyExist != ''" class="alert alert-danger">
{{emailAlredyExist}}
</div>
Component FIle
emailAlredyExist = "";
emailCheckUnique() {
this.ss.emailCheckUnique(this.angForm.controls['s_email'].value).subscribe(res => {
this.studentEmailcheck = res;
if (this.studentEmailcheck.length > 0) {
this.emailAlredyExist = "Email Alredy Exist";
}
else{
this.emailAlredyExist = "";
}
});
}
Service File
emailCheckUnique(email) {
return this
.http
.get(`${this.uri}/email/${email}`);
}
Nodejs Router File
studentRoutes.route('/email/:email').get(function (req, res) {
let email = req.params.email;
Student.find({s_email: email}, function (err, student){
res.json(student);
});
});
Anil
I miss my life when there is nothing to do, I look forward for an interesting and fun life with learning.
Updated on June 22, 2022Comments
-
Anil almost 2 years
I am creating an angular app in which a user can register. But while registering I request him for some details like email, mobile number and all. Also, a username which he can choose. But here I want to do a check on the username as soon as he entered and display an error like," this username already exists in our database".
I have mysql database and front end with angular 4. I am new to this angular development, please help me how can i do this?