How to make ngMessage for required fields only show when dirty or submitting a form?

前端 未结 12 2485
一个人的身影
一个人的身影 2020-12-08 02:31

I\'m using AngularJS 1.3.0 RC0 and angular-messages. ng-messages dutifully shows error messages for those \"required\" fields when a form is initially loaded and pristine. S

相关标签:
12条回答
  • 2020-12-08 02:38

    I solved this problem with a css rule

    [ng-messages] { display: none; color:red; } 
    .ng-dirty [ng-messages] { display:block }
    

    That's it..

    Works like a charm for me.

    Here is a plunker

    Angular's use of classes is amazing, you can do so many things with it!

    0 讨论(0)
  • 2020-12-08 02:42

    The best way to do this is with $touched:

    <div class="help-block" ng-messages="userForm.name.$error" ng-show="userForm.name.$touched">
        ...
    </div>
    
    0 讨论(0)
  • 2020-12-08 02:42

    Do the error messages still appear after you have satisfied their conditions? In that case, have you remembered to take a dependency on ngMessages in your angular module? E.g.:

    angular.module("exampleModule", ["ngMessages"]);
    
    0 讨论(0)
  • 2020-12-08 02:42
    <input required type="text" ng-model="model" name="field" ng-maxlength="13" ng-minlength="10">     
    <div ng-messages="form.field.$error" ng-if='form.$submitted'>
                <p ng-message="required">Required</p>
                <p ng-message="maxlength">not a valid field. Length exceeds.</p>
                <p ng-message="minlength">not a valid field. Length is shorter.</p>
    </div>
    

    button type should be submit and this will work.

    0 讨论(0)
  • 2020-12-08 02:52

    Use the ng-if attribute to check for $dirty on the tag that has ng-messages.

    Example :

    <div ng-messages='myForm.myControl.$error' ng-if='myForm.myControl.$dirty'>
        <div ng-message='required'>Required field</div>
    </div>
    
    0 讨论(0)
  • 2020-12-08 02:54

    I did not want to show my message until there is any error or user tried to submit the page, and none of the above solution worked.

    Finally I ended up successfully with this:

    <form name='frmUser'>
    ..........
    ..........
    <div ng-messages="frmUser.firstName.$error" 
         ng-show='frmUser.$submitted || frmUser.firstName.$dirty' role="alert">
          <div ng-message="required" class="err">Required</div>
          <div ng-message="maxlength" class="err">Maximum 50 characters.</div>
    </div>
    <input ng-model="model.first"
           name="firstName"
           type="text"
           ng-required="true"
           ng-maxlength="50"
           placeholder="Enter your first name" />
    
    </form>
    

    If you type anything which is not valid, then show the error

    If you try to submit the page and you have not provided the required field it will show error.

    0 讨论(0)
提交回复
热议问题