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

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

如何实现这个?

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

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

  1. <form ng-submit="submit()" name="form" ng-controller="MyCtrl">
  2. <div>
  3. <input type="email" name="email" ng-model="user.email" required />
  4. <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
  5. Email is required
  6. </span>
  7. </div>
  8.  
  9. <div>
  10. <button type="submit">Submit</button>
  11. </div>
  12. </form>
  1. function MyCtrl($scope){
  2. $scope.submit = function(){
  3. // Set the 'submitted' flag to true
  4. $scope.submitted = true;
  5. // Send the form to server
  6. // $http.post ...
  7. }
  8. };

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

  1. function MyCtrl($scope){
  2. $scope.submit = function(){
  3. // Set the 'submitted' flag to true
  4. $scope.submitted = true;
  5. // Send the form to server
  6. // $http.post ...
  7. }
  8.  
  9. $scope.hasError = function(field,validation){
  10. if(validation){
  11. return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
  12. }
  13. return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
  14. };
  15.  
  16. };
  1. <form ng-submit="submit()" name="form">
  2. <div>
  3. <input type="email" name="email" ng-model="user.email" required />
  4. <span ng-show="hasError('email','required')">required</span>
  5. </div>
  6.  
  7. <div>
  8. <button type="submit">Submit</button>
  9. </div>
  10. </form>

猜你在找的Angularjs相关文章