mrkernelpanic
mrkernelpanic

Reputation: 4471

Angular Form Email Validator not working as expected

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?

Upvotes: 17

Views: 22652

Answers (4)

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>

Upvotes: 5

Krishna Rathore
Krishna Rathore

Reputation: 9687

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;
    }
  }

Upvotes: 6

Chellappan வ
Chellappan வ

Reputation: 27471

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

Upvotes: 16

Suren Srapyan
Suren Srapyan

Reputation: 68685

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.

Upvotes: 1

Related Questions