自定义指令未验证表单。为什么不呢?

时间:2015-10-28 23:21:36

标签: javascript angularjs validation

需要进行哪些更改以获取下面的自定义countparens指令,以便在表单验证期间提供下面显示的额外自定义字符串验证?以下代码在成功提醒用户时输入字段为空,但是当打开的parens (和close parens )的数量不相等时,它不会提醒用户。

我正在使用AngularJS。我使用the documentation at this link (scroll to bottom)来设计下面的代码。

以下是表单的html:

<table>
    <tr>
        <td width=200>
            <form name="userForm" ng-submit="rectangularForm(userForm.$valid)" novalidate>
                <input type="text" name="fieldname" ng-model="nameofjsontype.fieldname" required />
                <p ng-show="userForm.fieldname.$invalid && !userForm.fieldname.$pristine" class="help-block">Function is a required field.</p>
                <span ng-show="userForm.nameofjsontype.fieldname.$error.countparens">The #( != #) !</span>
                <br>
                <button type="submit" ng-disabled="userForm.$invalid" >Click to submit</button>
            </form>
        </td>
    </tr>
</table>

包含该指令的javascript文件包括:

// create angular app
var myApp = angular.module('myApp', []);

// create angular controller
myApp.controller('myController', ['$scope', '$http', function($scope, $http) {
$scope.nameofjsontype = {type:"nameofjsontype", fieldname: 'some (value) here.'};

    $scope.rectangularForm = function(isValid) {
        // check to make sure the form is completely valid
        if (isValid) {
          var funcJSON = {type:"nameofjsontype", fieldname: $scope.nameofjsontype.fieldname};
          $http.post('/server/side/controller', funcJSON).then(function(response) {
            $scope.nameofjsontype = response.data;
          });
        }
    };
}]);

myApp.directive('countparens', function() {
 return {
   require: 'ngModel',
   link: function(scope, elm, attrs, ctrl) {
     ctrl.$validators.countparens = function(modelValue, viewValue) {
       if (ctrl.$isEmpty(modelValue)) {
         // consider empty models to be valid
         return true;
       }

       if (
        ($scope.nameofjsontype.fieldname.match(/\)/g).length) == ($scope.nameofjsontype.fieldname.match(/\(/g).length)
        ) {
         // it is valid
         return true;
       }

       // it is invalid
       return false;
     };
   }
 };
});

1 个答案:

答案 0 :(得分:2)

您的标记应使用userForm.fieldname.$error.countparens来显示错误。绑定到userForm的字段与您的ngModel值不同。请参阅plunker了解我的意思

<span ng-show="userForm.fieldname.$error.countparens" class="help-block">The #( != #) !</span>

您也没有在输入元素上使用您的指令:

<input type="text" name="fieldname" ng-model="nameofjsontype.fieldname" required data-countparens=""/>

在你的指令

  • 在进行匹配AND
  • 时,您应该使用modelValue而不是范围值
  • 当您与()
  • 无匹配时,您需要提供帮助

myApp.directive('countparens', function() {
    return {
      require: 'ngModel',
      link: function(scope, elm, attrs, ctrl) {
          ctrl.$validators.countparens = function(modelValue, viewValue) {
            return ctrl.$isEmpty(modelValue) ||
              ((modelValue.match(/\)/g) || []).length == (modelValue.match(/\(/g) || []).length);
          };
        }
    };
});