gpt4 book ai didi

javascript - 如何在 AngularJS 中显示数组表单字段的验证错误?

转载 作者:行者123 更新时间:2023-11-30 12:30:40 25 4
gpt4 key购买 nike

我创建了一个动态表单,其中有作为数组提交的重复字段。但是,我想单独验证每个字段并在其旁边显示错误消息。如果我只有一行,它工作正常,但一旦我添加第二行,第一行就会停止显示错误。

<form name='user' id='user' novalidate>
<div ng-repeat="bonus in bonuses">
<input name='codes[]' ng-model="bonus.code" lower-than="{{bonus.end_code}}" />
<input name='end_codes[]' ng-model="bonus.end_code" />
<span class="text-error" ng-show="user['codes[]'].$error.lowerThan">
Code must be less than End Code.
</span>
</div>
</form>

AngularJS

var app = angular.module('newBonus', []);

app.controller('NewBonusController', function($scope) {
$scope.bonuses = [];

$scope.addFields = function () {
$scope.bonuses.push({code:'', end_code: ''});
}

$scope.submit = function(){
console.log($scope.bonuses);
}
});


// Validate that one field is less or equal than other.
app.directive('lowerThan', [
function() {

var link = function($scope, $element, $attrs, ctrl) {

var validate = function(viewValue) {
var comparisonModel = $attrs.lowerThan;

if(!viewValue || !comparisonModel){
// It's valid because we have nothing to compare against
ctrl.$setValidity('lowerThan', true);
}

// It's valid if model is lower than the model we're comparing against
ctrl.$setValidity('lowerThan', viewValue <= comparisonModel );
return viewValue;
};

ctrl.$parsers.unshift(validate);
ctrl.$formatters.push(validate);

$attrs.$observe('lowerThan', function(comparisonModel){
return validate(ctrl.$viewValue);
});

};

return {
require: 'ngModel',
link: link
};

}
]);

笨蛋:http://plnkr.co/edit/Fyqmg2AlQLciAiQn1gxY

我可以满足于不将它放在每个字段旁边,只要对其他字段集的更改确实会正确触发错误消息,在这种情况下我可以将它弹出到顶部。我看到的主要问题是,因为它们是数组 codes[],最后传递给表单,所以它们将无法正常工作。

提交按钮在表单验证时被正确禁用,所以我不确定为什么消息只锁定到添加的最后一行。

最佳答案

使用子表单来分隔范围。

<ng-form name="frmChild">
<input name='codes' ng-model="bonus.code" lower-than="{{bonus.end_code}}" />
<input name='end_codes' ng-model="bonus.end_code" />
<span class="text-error" ng-show="frmChild.codes.$error.lowerThan">
Code must be less than End Code.
</span>
</ng-form>

关于javascript - 如何在 AngularJS 中显示数组表单字段的验证错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27805769/

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