Reputation: 759
How can I check if email exists in database using custom validator? I have tried to found built in validator but there is none for that purpose. I can't put code to question because I'm new to angular 2 and I don't know how to use custom validators.
In component I get all users from database and I need to check if email entered in input form already existis.
ngOnInit() {
this.registrationService.getUsers().subscribe(data => this.allUsers = data, error => this.errorMsg = error);
}
in service:
AddUser(regValues: any, allUsers: any) {
if (regValues.email !== "" || regValues.password !== "" || regValues.nickname !== "" || regValues.confirmpassword !== "") {
if (regValues.password != regValues.confirmpassword) {
window.alert("Password and confirm password don't match. Please input same password in these two fields.");
}
else if (regValues.password.length < 7) {
window.alert("Password must have minimum 7 characters. Please input password that has apropriate length.");
}
else if (regValues.username.length < 3) {
window.alert("Nickname must have minimum 3 characters. Please input nickname that has apropriate length.");
}
else {
if (allUsers.indexOf(regValues.email) !== -1) {
window.alert("This email is already taken. Please choose another one.");
}
var regUser = {
Email: regValues.email,
PasswordHash: undefined,
UserName: regValues.username
}
regUser.PasswordHash = Md5.hashStr(regValues.password);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('/footballapi/user/add', regUser, options)
.map((response: Response) => response.json())
.catch(this.registrationService.errorHandler);
}
}
}
In component:
Register(regValues: any) {
let allUsers = this.registrationService.getUsers();
this.registrationService.AddUser(regValues, allUsers).subscribe(data => this.allUsers = data, error => this.errorMsg = error);
}
HTML form:
<h4>Create a new account.</h4>
<p>{{errorMsg}}</p>
<hr />
<form #registrationForm="ngForm" (ngSubmit)="Register(registrationForm.value)">
<div class="form-group">
<label for="email">Email:</label>
<div class="col-md-10">
<input type="text" name="email" ngModel required placeholder="Write your email address here..." />
</div>
</div>
<div class="form-group">
<label for="email">Nickname:</label>
<div class="col-md-10">
<input type="text" name="nickname" ngModel required placeholder="Write your nickname here..." />
</div>
</div>
<div class="form-group">
<label for="password">Password:</label>
<div class="col-md-10">
<input type="password" name="password" ngModel required placeholder="Write your password here..." />
</div>
</div>
<div class="form-group">
<label for="confirmpassword">Confirm password:</label>
<div class="col-md-10">
<input type="password" name="confirmpassword" ngModel required placeholder="Write your password again..." />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" [disabled]="!registrationForm.form.valid">Confirm registration</button>
</div>
</div>
</form>
Upvotes: 1
Views: 2179
Reputation: 485
You can achieve this by using Async Validator
You have to write a Validator function, make a call to database and return a variable to say weather the email exists or not.
import {Control} from "@angular/common"
export class EmailValidators{
static checkEmail(control: Control){
// make a db call{
// if exists
return {checkEmail : true}
}else return null;
}
}
Then this returned boolean flag will be passed as the aync validator parameter if you use model driven forms and using formbuilder, include this in your component
export calss AppComponent{
constructor(fb : FormBuilder){
this.form = fb.group({
email:['',Validators.EmailValidators.checkEmail]
})
}
}
Here is EmailValidators is the class that u import and checkEmail is the static method used to define your custom validation, which returns the boolean.
Upvotes: 3