Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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 – 仅在提交或用户输入时验证表单字段全部内容,希望文章能够帮你解决angularjs – 仅在提交或用户输入时验证表单字段所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。