I have a very simple form with just one input field:
this.form = this.fb.group({
emailAddress: ['', [Validators.required, Validators.email]],
});
Markup:
<input type="email" class="form-control" formControlName="emailAddress">
This field has two validators, required and for emails.
I also have a submit button that is configured as follows:
<button [disabled]="!form.valid" type="submit">Send</button>
The confusing part is that when I input a wrong email address like:
a@b
the submit button gets enabled, thus marking the form and input field as valid. I expect that a@b
is not a valid email address.
Is there any other Email Validator in angular that I should use or is this a bug?
for angular just add the atribute "email" like this :
<label for="email">Email</label>
<input type="email" id="email" name="email" #email="ngModel"
ngModel class="form-control" email required>
<span class="help-block" *ngIf="!email.valid && email.touched">
Email is invalid
</span>
You can use pattern to implement valid email
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', [Validators.required, Validators.email,Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$')]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
Example:https://stackblitz.com/edit/angular-email-validation
You can use custom email validation
I have create a demo on Stackblitz
Component.html
<form [formGroup]="myForm">
<input type="email" class="form-control" formControlName="emailAddress" placeholder="Enter email">
<button [disabled]="!myForm.valid" type="submit">Send</button>
</form>
Component.ts
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
emailAddress: [null, [Validators.required, this.emailValidator]]
});
}
emailValidator(control) {
if (control.value) {
const matches = control.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
return matches ? null : { 'invalidEmail': true };
} else {
return null;
}
}
It is a valid email address and so why it pass validation. If it does not satisfy, you can create your own validator and implement your logic there.
You can read more Custom Validators and try to implement yours.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With