gpt4 book ai didi

javascript - 自定义指令不验证表单。为什么不?

转载 作者:行者123 更新时间:2023-12-02 15:29:54 25 4
gpt4 key购买 nike

需要进行哪些代码更改才能获取下面的自定义 countparens 指令,以便在表单验证期间提供下面所示的额外自定义字符串验证? 下面的代码确实成功发出警报当输入字段为空时,它不会提醒用户,但当左括号 ( 和右括号 ) 的数量不相等时,它不会提醒用户。

我正在使用 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;
};
}
};
});

最佳答案

您的标记应使用userForm.fieldname.$error.countparens来显示错误。绑定(bind)到 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);
};
}
};
});

关于javascript - 自定义指令不验证表单。为什么不?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33403304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com