I have made a basic form using angular material and would like to have specific error messages pop up when an input is invalid. I tried to model it after the input example on the official website, which uses the ng-messages
directive to display the validation errors. For whatever reason, error messages only seem to get shown when the validation state transitions from valid to invalid.
For example, there is an input like <input type="email" required>
with an <ng-message when="email">
that says "Please enter a valid email." Writing an invalid email and then tabbing away to the next value triggers validation, the invalid style gets applied to the input and the message gets shown. If instead I immediately proceed to the next input without entering anything the element also gets the invalid style applied (because of the required
attribute) and no message appears as expected (I did not include one for required
). But if I focus the input again and write an invalid email, the message does not show up (even if I move focus away and back). The input element still has the invalid style applied to it however. The message only shows up again when I write an invalid email (causing the invalid style to be removed from the element) and then delete it to make it invalid again.
Here is an example CodePen which shows his behavior, and displays the values of the form attributes. The markup is:
<div ng-app="TestApp" layout="row" layout-align="center">
<div class="md-whiteframe-6dp md-margin" layout="column" flex="33">
<md-toolbar>
<div class="md-toolbar-tools">
<h3>Sign Up</h3>
</div>
</md-toolbar>
<md-content class="md-padding">
<form name="signupForm" class="md-inline-form">
<div layout-gt-xs="row">
<md-input-container flex>
<label>Username</label>
<input name="username" ng-model="user.username" required ng-minlength="6" autofocus/>
<ng-messages for="signupForm.username.$error">
<ng-message when="minlength">
Username must be at least 6 characters
</ng-message>
</ng-messages>
</ng-input-container>
</div>
<div layout-gt-xs="row">
<md-input-container flex>
<label>Email</label>
<input type="email" name="email" ng-model="user.email" required/>
<ng-messages for="signupForm.email.$error">
<ng-message when="email">
Please give a valid email
</ng-message>
</ng-messages>
</ng-input-container>
</div>
<div layout="column" layout-gt-xs="row" layout-align="center">
<md-button type="submit" class="md-raised md-primary">
Register
</md-button>
<md-button type="button" class="md-primary">
Back to sign in
</md-button>
</div>
</form>
</md-content>
</div>
</div>
The javascript is nothing but
angular.module("TestApp", ["ngMaterial", "ngMessages"]);
You can see the inputs are being correctly validated, but it looks like the message elements aren't having the right styles applied to them (opacity: 1
) when they should.