How to Validate & Display Error Message - Angular2 Material Design?
Solution 1
Hopefully this will be added as angular2-material evolves, but currently the way to mimic this is to set the dividerColor and use the MD-HINT directive. example:
<md-input placeholder="Email address"
#email="ngModel"
name="email"
type="text"
fullWidth={true}
[(ngModel)]="model.email"
required
email
dividerColor="{{ !email.valid ? 'warn' : 'primary' }}">
<md-hint [hidden]="email.pristine || email.valid">
<span [hidden]="email.errors?.required || !email.errors?.email">
This doesn't appear to be a valid email address.
</span>
<span [hidden]="!email.errors?.required">Email address is required.</span>
</md-hint>
</md-input>
Solution 2
Validation messages can now be inserted with Angular Material version 2.0.0 onward. Check the documentation here.
<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="Email" [formControl]="emailFormControl">
<mat-error *ngIf="emailFormControl.hasError('pattern')">
Please enter a valid email address
</mat-error>
<mat-error *ngIf="emailFormControl.hasError('required')">
Email is <strong>required</strong>
</mat-error>
</mat-form-field>
</form>
Vicheanak
I'm a Javascript full stack developer experiencing in NodeJS, Angular1, Angular2, Ionic1, Ionic2 and JQuery. I'm also very experienced in Linux Server such as setting up development environment and deployment procedure. I'm a big fan of Git and VIM is his favorite editor.
Updated on June 14, 2022Comments
-
Vicheanak almost 2 years
I have this input:
<form #f="ngForm" name="productForm"> <md-input [(ngModel)]="product.price" name="price" required="true" placeholder="Price (USD)"></md-input> <div ng-messages="productForm.price.$error" role="alert"> <div ng-message-exp="['required']"> Price is required </div> </div> </form>
But the message Price is required doesn't show up.
How should I properly format the error message?
The ng-invalid class appears when the price input is empty:
Angular injects ng-valid class in it.
I want is to have the style similar to angular1 md design that looks like this:
-
Vicheanak over 7 yearsexcuse me, what do you mean by, !email.errors?.email?
-
angularrocks.com over 7 yearsdiscussion about one this one is on official material2 repo github.com/angular/material2/issues/348
-
cport1 about 7 yearsyou might want to edit the answer for the latest version. dividerColor now needs to be part of md-input-container instead of md-input
-
Viktor Eriksson over 6 yearsIs it possible to make the error show while typing and not when bluring the input field. I know that if I blur it and then type it will validate as I type, but is it possible to get it to show me the error message while typing the first time I enter the input field ?
-
Reza Taba over 3 yearsYes @ViktorEriksson. It is. I'll leave it as a solution.