[英]custom directive is not validating form. why not?
为了获得下面的自定义countparens
指令,需要进行哪些代码更改,以在表单验证期间提供下面显示的额外的自定义字符串验证? 当输入字段为空时,下面的代码可以成功地警告用户,但是当打开的括号(
和关闭的括号)
数量不相等时,它不会警告用户。
我正在使用AngularJS。 我使用此链接处的文档(滚动至底部)来设计以下代码。
这是表单的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;
};
}
};
});
您的标记应该使用userForm.fieldname.$error.countparens
来显示错误。 绑定到userForm
的字段与您的ngModel
值不同。 见笨蛋我的意思
<span ng-show="userForm.fieldname.$error.countparens" class="help-block">The #( != #) !</span>
您还没有在输入元素上使用指令:
<input type="text" name="fieldname" ng-model="nameofjsontype.fieldname" required data-countparens=""/>
在您的指令中
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);
};
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.