in this plunk there's a form with ngMessage validations. This is what I'm trying to achieve:
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');
};
});
You need to display validation messages using condition like e.g. ng-if
HTML:
<div ng-if="submitted || myForm.myName.$dirty"
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>
Javascript:
$scope.submitForm = function() {
$scope.submitted = true;
if (myForm.$valid) {
alert('Form submitted - fields passed validation');
}
};
and move ng-submit from button to form tag like:
<form name="myForm" novalidate ng-submit="submitForm()">
Based on Kwarc's anwser, here is a little improvement since you can avoid using a $scope
variable to know if your form is submitted. It also ensure a better behavior on error message display.
HTML:
<div ng-if="myForm.myName.$invalid && (myForm.$submitted || myForm.myName.$touched)"
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>
Javascript:
$scope.submitForm = function() {
if (myForm.$valid) {
alert('Form submitted - fields passed validation');
}
};
myForm.$submitted
will be automatically set to true
and finally, apply the same form submit method on form tag:
<form name="myForm" novalidate ng-submit="submitForm()">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With