I've been trying to implement validation in my app, but I'm facing some issues with getting it to work correctly. My goal is to display a message "email is required" when the user leaves the email input empty (even if they make changes), and show "email is invalid" when the entered email does not match the specified pattern.
I have experimented with various combinations, but I am unsure of which approach is best. That's why I initially opted for a simple implementation. Perhaps someone has a better solution for this?
Component:
public accountForm: FormGroup;
constructor(private router: Router, private formBuilder: FormBuilder) {
}
get formControls() { return this.accountForm.controls; }
ngOnInit() {
this.accountForm = this.formBuilder.group({
email: [
null,
[
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
]
]
});
}
..
Html:
...
<form novalidate [formGroup]="accountForm">
<div class="input-group mb-3 flex-nowrap">
<input type="text" class="form-control" placeholder="Email" id="email" formControlName="email">
</div>
<div *ngIf="formControls.email.required" class="input-error">Email is required</div>
<div *ngIf="formControls.email.invalid && formControls.email.touched" class="input-error">Email is invalid</div>
...
Currently, only the validation with the pattern is functioning properly, while I am struggling to implement the required validation.