I'm working on implementing email validation in an Angular 2 form, but I'm facing some challenges making it function properly.
Below is the code snippet from my register.html form:
<div class="row">
<div class="col-lg-10 col-offset-2">
<div class="well bs-component">
<form name="registerForm" class="form-horizontal" (ngSubmit)="onSubmit(email, password, name, surname, username, homephonenumber, mobilenumber)" >
<fieldset>
<legend>Register</legend>
<div class="form-group">
<label for="username" class="col-lg-2 control-label">UserName</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="username" [(ngModel)]="username" placeholder="Username" required minlength="4" maxlength="20">
</div>
</div>
<div class="form-group">
<label for="email" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="email" [(ngModel)]="email" placeholder="Email" required minlength="4" >
<div *ngIf="email.dirty && !email.valid" class="alert alert-danger">
<p *ngIf="email.errors.required">Email address is required.</p>
<p *ngIf="email.errors.incorrectMailFormat">Email format is invalid.</p>
</div>
</div>
</div>
<div class="form-group">
<label for="password" class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" class="form-control" name="password" [(ngModel)]="password" placeholder="Password" required minlength="4">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="reset" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Register</button>
</div>
</div>
</fieldset>
</form>
</div>
In my register.component.ts file, the following code is implemented:-
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {UserService} from 'app/services/user.service';
import {FormGroup, FormControl, Validators} from "@angular/forms";
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
registerForm: FormGroup;
constructor(private _userService:UserService, private _router:Router) { }
ngOnInit() {
this.registerForm = new FormGroup({
email: new FormControl('', this.validateEmail)
});
}
onSubmit(email, password, name, surname, username, homephonenumber, mobilenumber){
this._userService.register(email, password, name, surname, username, homephonenumber, mobilenumber)
.subscribe((result) => {
// if(result.access_token != null) {
// this._router.navigate(['']);
// }
});
}
validateEmail(c: FormControl) {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
return EMAIL_REGEXP.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
}
Do I need to add any additional configurations to ensure the validation functions correctly?
Thank you for your assistance and time.