单击提交时如何在md-input-container中显示突出显示错误?

时间:2016-02-29 08:21:13

标签: javascript angularjs angular-material

我已更新材料,然后我更新了我的代码

<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>

当我弄脏场时,它会突出显示输入;但是,我想点击提交按钮并在输入上显示突出显示,即使我没有弄脏所需的字段。

这是我的傻瓜 http://plnkr.co/edit/oAWaFr8OtBusRli4v8MS?p=preview 我想单击“保存”按钮,然后在输入字段上显示错误突出显示。

2 个答案:

答案 0 :(得分:2)

您必须添加type="submit"以使用表单绑定您的保存按钮,这意味着您将提交表单。

来自你的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>

在保存按钮上触发角度功能将ng-submit添加到表单

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

更新了plunkr

答案 1 :(得分:1)

更新您的html,如下所示

<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>

在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