How to show highlight error in md-input-container when click submit?

别说谁变了你拦得住时间么 提交于 2019-12-23 04:56:21

问题


I have updated material then I update my code like that

<md-input-container>
    <label>Last Name</label>
    <input name="lastName" ng-model="lastName" required>
    <div ng-messages="userForm.lastName.$error" ng-show="userForm.lastName.$dirty">
      <div ng-message="required">This is required!</div>
    </div>
</md-input-container>

It will highlight on the input when I dirty the field; however, I want to click on submit button and show highlight on the input even I don't dirty that required field.

Here is my plunker http://plnkr.co/edit/oAWaFr8OtBusRli4v8MS?p=preview I want to click on Save button and then show error highlight on the input field.


回答1:


You have to add type="submit" to bind your save button with form that means you are going to submit your form.

From your plunkr

<form name="userForm" novalidate>
  <md-input-container>
    <label>Last Name</label>
    <input name="lastName" ng-model="lastName" required>
    <div ng-messages="userForm.lastName.$error " ng-show="userForm.lastName.$dirty || userForm.$submitted" >
      <div ng-message='required'>This is required!</div>
    </div>
  </md-input-container>

  // added type="submit"
  <md-button type="submit" class="md-raised md-primary">Save</md-button>
</form>

to fire angular function on save button add ng-submit to your form

<form name="userForm" ng-submit="save()" novalidate>

Updated plunkr




回答2:


Update your html as below

<form name="userForm" novalidate>
  <md-input-container>
    <label>Last Name</label>
    <input name="lastName" ng-model="lastName" required>
    <div ng-messages="userForm.lastName.$error " ng-show="userForm.lastName.$touched || submitted" >
      <div ng-message='required'>This is required!</div>
    </div>
  </md-input-container>

  <md-button class="md-raised md-primary" ng-click="validate()">Save</md-button>
</form>

Add a custom validation function inside your Controller

  $scope.submitted = false; //use this variable to check for validation

  //call this function instead of your action on form submit.
  $scope.validate = function(){
    if(!$scope.user.firstName.length){
      $scope.submitted = true;
      //your action here
    }
    else{
      $scope.submitted = true;
    }
  }

PLUNK HERE



来源:https://stackoverflow.com/questions/35694777/how-to-show-highlight-error-in-md-input-container-when-click-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!