Angular使用ng-messages与PHP进行表单数据验证

Angular中的ng-messages提供了更方便的表单数据验证服务。

本文代码主要基于《AngularJS权威教程》中关于ng-messages模块的说明,但原文中不乏错误以及没有后台代码和示例,所以简单的实现其功能。//别的地方也有错误,我一度怀疑我买了盗版书==

比如我们想与后台进行表单数据合法性验证并给出输入操作提示

HTML代码:

<!DOCTYPE html>
<html lang="en" ng-app="app">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="angular.js"></script>
  <script src="angular-messages.js"></script>
  <script>
  angular.module("app", ["ngMessages"])
    .directive("ensureUnique", function($http) {
      return {
        require: "?^ngModel",
        //原文中混用了ngModel和ctrl,这里统一使用ngModel,意指ngModelController
        link: function(scope, element, attrs, ngModel) {


          var url = attrs.ensureUnique;
          if (!ngModel) {
            return false;
          }
          ngModel.$parsers.push(function(val) {
            if (!val || val.length == 0) {
              return false;
            }

            //设置表单状态,属性统一归于signup_form.username.$error中,这是为设置是否合法状态,所以如果设置为false,则会在ng-messages中显示,因为它调用的是$error方法,意为是否“不合法”,原文有错误。
            ngModel.$setValidity("checkingAvailability", false);
            ngModel.$setValidity("usernameAvailability", true);

            $http({
              method: "POST",
              url: url,
              data: {
                username: val
              }
            }).then(function(r) {
              if ("exist" == r.data) {
                ngModel.$setValidity("checkingAvailability", true);
                ngModel.$setValidity("usernameAvailability", false);
              } else {
                ngModel.$setValidity("checkingAvailability", true);
                ngModel.$setValidity("usernameAvailability", true);
              }
            }, function(e) {
              console.log(e);
            })

            return val;
          })
        }
      }
    })
    .controller("MainController", function($scope) {
      $scope.signup = {
        username: ""
      }
    })
  </script>
</head>

<body>
  <div ng-controller="MainController">
    <form name="signup_form" novalidate ng-submit="signupForm()">
      <!-- 原文中指令放在了form元素中,应该放在input元素中 -->
      <input type="text" name="username" ng-model="signup.username" required ng-min-length=3 ng-max-length=10 ensure-unique="check.php">
      <!-- 输入过才显示操作信息 -->
      <div class="error" ng-show="signup_form.$dirty" ng-messages="signup_form.username.$error" ng-messages-multiple>
        <div ng-message="required">
          Required!!!
        </div>
        <div ng-message="checkingAvailability">
          Checking...
        </div>
        <div ng-message="usernameAvailability">
          Has been taken, please choose another.
        </div>
      </div>
      <div>
        <button type="submit">Submit</button>
      </div>
      <p>{{signup_form.username.$error}}</p>
    </form>
  </div>
</body>

</html>

PHP代码:

<?php

  //Angular与jQuery传递参数类型不同,不能直接使用$.POST['username']获取;
  $postData = file_get_contents('php://input', true); 
  $obj=json_decode($postData);

  //这里模拟唯一性验证
  if($obj->username == '123'){
    echo "exist";
  }
  else{
    echo "available";
  }
?>

效果:

Angular使用ng-messages与PHP进行表单数据验证