angularjs – 仅在提交或用户输入时验证表单字段

前端之家收集整理的这篇文章主要介绍了angularjs – 仅在提交或用户输入时验证表单字段前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有使用required验证的表单字段。问题是,在呈现表单时立即显示错误。我想要它只显示用户实际输入文本字段后,或提交。

如何实现这个?

使用$ dirty标志仅在用户与输入交互后显示错误
<div>
  <input type="email" name="email" ng-model="user.email" required />
  <span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span>
</div>

如果只想在用户提交表单后触发错误,可以使用单独的标志变量,如:

<form ng-submit="submit()" name="form" ng-controller="MyCtrl">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
      Email is required
    </span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>
function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  } 
};

然后,如果所有在ng-showexpression中的JS看起来太多了,你可以将它抽象为一个单独的方法

function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  }

  $scope.hasError = function(field,validation){
    if(validation){
      return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
    }
    return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
  };

};
<form ng-submit="submit()" name="form">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="hasError('email','required')">required</span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>

猜你在找的Angularjs相关文章