in this plunk there's a form with ngMessage validations. This is what I'm trying to achieve:
- When the form is shown to the user, no error messages should be displayed
- On blur, if the field has errors, the message should be displayed
- When the form is submitted, if there are any fields with errors, then the error messages should be displayed.
In the plunk I have two issues: (1) the message is displayed when the form is initially shown, and (2) when no error messages and the user clicks on the button, the form is not submitted. What's wrong with the code?
HTML
<form name="myForm" novalidate>
<label>
Enter your name:
<input type="text"
name="myName"
ng-model="name"
ng-minlength="5"
ng-maxlength="20"
required />
</label>
<div ng-messages="myForm.myName.$error" style="color:red" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
<button type="submit"
ng-submit="myForm.$valid && submitForm()">Submit</button>
</form>
Javascript
var app = angular.module('ngMessagesExample', ['ngMessages']);
app.controller('nameController', function ($scope) {
$scope.submitForm = function() {
alert('Form submitted - fields passed validation');
};
});