How to show highlight error in md-input-container

2019-06-12 15:52发布

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.

2条回答
甜甜的少女心
2楼-- · 2019-06-12 16:10

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

查看更多
冷血范
3楼-- · 2019-06-12 16:29

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

查看更多
登录 后发表回答