AngularJS: 有没有办法确定哪些字段使表单无效?

我有下面的代码在 AngularJS 应用程序中,在一个控制器内, 这个函数属于一个名为 profileForm的表单:

$scope.updateProfile = function() {
if($scope.profileForm.$invalid) {
//error handling..
}
//etc.
};

在这个函数内部,有没有办法找出哪些字段导致整个表单被称为无效?

95076 次浏览

You can loop through form.$error.pattern.

$scope.updateProfile = function() {
var error = $scope.profileForm.$error;
angular.forEach(error.pattern, function(field){
if(field.$invalid){
var fieldName = field.$name;
....
}
});
}

When any field is invalid, if you try to get its value, it will be undefined.

Lets say you have a text input attached to $scope.mynum that is valid only when you type numbers, and you have typed ABC on it.

If you try to get the value of $scope.mynum, it would be undefined; it wouldn't return the ABC.

(Probably you know all this, but anyway)

So, I would use an array that have all the elements that need validation that I have added to the scope and use a filter (with underscore.js for example) to check which ones return as typeof undefined.

And those would be the fields causing the invalid state.

Each input name's validation information is exposed as property in form's name in scope.

HTML

<form name="someForm" action="/">
<input name="username" required />
<input name="password" type="password" required />
</form>

JS

$scope.someForm.username.$valid
// > false
$scope.someForm.password.$error
// > { required: true }

暴露的属性为$pristine$dirty$valid$invalid$error

如果您出于某种原因想要遍历错误:

$scope.someForm.$error
// > { required: [{$name: "username", $error: true /*...*/},
//                {$name: "password", /*..*/}] }

每个出错的规则都将在$error中公开。

这是一个用http://plnkr.co/edit/zCircDauLfeMcMUSnYaO?p=preview玩的Plunkr。

用于检查表单的哪个字段无效

console.log($scope.FORM_NAME.$error.required);

这将输出表单的无效字段的数组

如果您想查看哪些字段与您的验证发生了冲突,并且您有jQuery来帮助您,只需在JavaScript控制台上搜索“ NG-无效”类。

$('.ng-invalid');

它将列出所有因任何原因未能通过验证的DOM元素。

我想在禁用的保存按钮工具提示中显示所有错误,这样用户就会知道为什么禁用而不是上下滚动长表单。

注意:请记住将名称属性添加到表单中的字段

    if (frm) {
disable = frm.$invalid;
if (frm.$invalid && frm.$error && frm.$error.required) {
frm.$error.required.forEach(function (error) {
disableArray.push(error.$name + ' is required');
});
}
}
if (disableArray.length > 0) {
vm.disableMessage = disableArray.toString();
}

对于我的应用程序,我显示的错误如下:

<ul ng-repeat="errs in myForm.$error">
<li ng-repeat="err in errs">\{\{err.$name}}</li></ul>

如果您想查看所有内容,只需使用' err ',它将显示如下内容:

 "$validators": {},
"$asyncValidators": {},
"$parsers": [],
"$formatters": [],
"$viewChangeListeners": [],
"$untouched": true,
"$touched": false,
"$pristine": true,
"$dirty": false,
"$valid": false,
"$invalid": true,
"$error": { "required": true },
"$name": "errorfieldName",
"$options": {}

格式没有这么好,但你会在那里看到这些东西……

如果您想要查找不以编程方式使UI上的表单无效的字段,只需右键单击Inspect(在元素视图中打开开发人员工具),然后在此选项卡中使用Ctrl+F搜索NG-Invalid。然后,对于您发现NG-Invalid Class的每个字段,您可以检查该字段是否在必需时未被赋予任何值,或者它是否违反了其他规则(无效的电子邮件格式、超出范围/最大值/最小值定义等)。这是最简单的方法。