Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 material design for email validation

Hi I am trying to implement form validation using material design with Angular 2. Here is the input field :

<md-input-container class="example-full-width" 
          dividerColor="{{username.untouched || username.valid?'primary':'warn'}}">
          <input mdInput placeholder="Email" type="email" name="username" id="username"
            #username="ngModel" required 
            [(ngModel)]="loginModel.username">
        </md-input-container>

I the above code, I am trying to put red color bottom border if:

  1. Field is touched and required filed condition is not met

  2. Field is touched and there is invalid email string

The first condition is being fulfilled using username.untouched || username.valid?'primary':'warn' but unable to validate email. Any suggestion.

Edit : I tried using <md-hint> as:

<md-hint *ngIf="username.errors &&(username.dirty || username.touched)">
              <span [hidden]="username.errors?.required || !username.errors?.email">Invalid email</span>
              <span [hidden]="!username.errors?.required">Required.</span>
            </md-hint>

It is working fine for Required but not for incorrect email.

like image 826
Vivek Avatar asked Apr 22 '26 16:04

Vivek


1 Answers

Use <md-error>, and you don't have to worry about error validation styles.

HTML:

<md-input-container>
    <input mdInput placeholder="email" [formControl]="emailFormControl" required>
    <md-error *ngIf="emailFormControl.hasError('required')">
    This field is required
    </md-error>
    <md-error *ngIf="emailFormControl.hasError('pattern')">
    Please enter a valid email address
    </md-error>
</md-input-container>

TS:

import { FormControl, Validators, NgModel } from '@angular/forms';

const EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
export class FormlayoutComponent {
    private emailFormControl = new FormControl('', [Validators.required, Validators.pattern(EMAIL_REGEX)]);
....
}

Hope this helps.

like image 66
SatAj Avatar answered Apr 25 '26 09:04

SatAj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!