Aanchal Aanchal - 1 year ago 109
AngularJS Question

ng- message is not displaying message properly

I am doing validation using angular js and trying to display error messages through ng-message directive. But my issue is that in my form when I enter any error input , it does not display message at first time and when I click anywhere outside the form then only its displaying messages.Also I want that when error is removed then original label should appear. But here once error message is shown , then label don't appear in my form. I am using below code for validation-

<div class="form-group" ng-class="{ 'has-error' : myForm.num.$invalid && (myForm.$submitted || myForm.num.$touched ) || myForm.num.$error.minlength || myForm.num.$error.maxlength || myForm.num.$error.pattern}">

<label for="Number" style="color:#767676" class=""
ng-hide="myForm.num.$invalid && (myForm.$submitted || myForm.num.$touched || myForm.num.$error.minlength || myForm.num.$error.pattern)">Number</label>

<div ng-show="myForm.num.$touched " ng-messages="myForm.num.$error">
<label class="error_message_text" ng-message="required">required field</label>
<label class="error_message_text" ng-message="minlength">too short</label>
<label class="error_message_text" ng-message="pattern">wrong pattern</label>
<input type="text" numbers-only name="num" class="form-control" ng-class="" ng-minlength="7" ng-maxlength="9"
ng-model="user.name" ng-pattern="/^\d{7}$|^\d{9}$/" required/>


I have created a plunker here-

Can anyone help me in my validation where I am missing?

Answer Source

Use both dirty and error valid,

 <div ng-show="myForm.num.$invalid && myForm.$submitted" ng-messages="myForm.num.$error">

See this plunker,but I have removed your number validation code that made problems during required validations https://plnkr.co/edit/3m0zLJ2PhAruSFxStwmt?p=preview

Updated Final Answer- https://plnkr.co/edit/v65oGQaZ64nU25EhX2nz?p=preview

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download