[英]Proper way to display form validation errors in Angular?
如果触发了验证错误,我将在页面顶部显示警报,当错误修复后,当前的实现也会隐藏该错误。 一切正常,但效率低下,有没有更好的方法?
HTML:
<div class="alert alert-danger"
ng-repeat error in advAlerts
ng-show="error.hasError()">
{{error.text}}
</div>
JS:
$scope.advAlerts = [
{
hasError: checkFooError,
text: 'Error Foo',
},
{
hasError: checkBarError,
text: 'Error Bar',
},
...
]
function checkFooError() {
//check a list of required attributes to see they're all filled out
//returns true/false
}
使用此方法,页面可以响应:单击提交后,如果缺少任何必需的属性,则会显示警报。 填写所有必需的属性后,警报立即消失。
但是,由于摘要周期(我认为?),checkFooError函数被称为“吨”,有没有更好的方法呢?
-编辑-
标准验证已经就绪,我忘了提到这些是“高级警报”,因为它们是设计人员想要的额外东西。
好了,您不必为AngularJS中的表单验证编写太多代码。 AngularJS为我们提供了一些可用于检查表单状态的属性。 因此,您可以从各个方面检查for及其控制器的状态。
表格状态:-
$valid
:验证表单是否与html控件中定义的规则匹配
$invalid
:根据定义的规则验证表单是否无效
$pristine
:如果用户未使用HTML控件/标记, $pristine
true
$dirty
:如果用户已使用HTML控件/标记, $dirty
true
用法示例:-
<div class="form-group" ng-class="{ 'has-error' : yourForm.username.$invalid && !yourForm.username.$pristine }">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8" required>
<p ng-show="yourForm.username.$error.required">Username is short.</p>
<p ng-show="yourForm.username.$error.minlength">Username is short.</p>
<p ng-show="yourForm.username.$error.maxlength">Username is long.</p>
</div>
<div class="form-group" ng-class="{ 'has-error' : yourForm.email.$invalid && !yourForm.email.$pristine }">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="user.email">
<p ng-show="yourForm.email.$invalid && !yourForm.email.$pristine" >Enter a valid email.</p>
</div>
参考: 表格的Angular文档
如果要避免在HTML中使用样板代码,则可以避免将所有这些ng-show和类似的内容放入表单中,从而将其与验证机制本身完全分离。
在客户端执行验证时,您不必一定要与angular捆绑在一起,可以将angularjs与任何其他JS框架组合在一起,并使它们与requireJS一起作为独立模块一起工作。 我一直在使用bootstrapValidator和angular,将它们与requireJS绑定在一起,它的性能很好,在html中为您提供了干净的代码,具有完全解耦的模块,当您使用$ viewContentLoaded加载视图时,可以附加一个侦听器,然后使用函数调用在您的表单上启用验证,我以示例代码为例:
干净的angularJS形式:
<form id="myForm" novalidate="novalidate" class="form-horizontal"> <label>name</label> <input type="text" class="form-control" id="name" name="name" ng-model="rec.name" /> <label>description</label> <textarea rows="5" id="description" ng-model="rec.description" name="description"> </textarea> // ... more fields
在您的控制器代码中:
controllers.controller('MyCtrl', ['$scope', 'MyService',
function($scope, MyService) {
// ... controller code
// setup validator based on your page form
$scope.$on('$viewContentLoaded', loadFormValidator);
}]);
function loadFormValidator(){
$('#myForm').bootstrapValidator({
message: 'The form has invalid inputs',
fields: {
name: {
message: 'The name is not valid',
validators: {
notEmpty: {
message: 'The name is required and can\'t be empty'
},
stringLength: {
min: 6,
max: 70,
message: 'The name must be more than 6 and less than 70 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9_\.\s]+$/,
message: 'The name can only consist of alphabetical, number, dot, spaces and underscore'
}
}
},
description: {
message: 'The description is not valid',
validators: {
notEmpty: {
message: 'The description is required and can\'t be empty'
},
stringLength: {
min: 6,
max: 160,
message: 'The description must be more than 6 and less than 160 characters long'
}
}
},
price: {
message: 'The price is not valid',
validators: {
notEmpty: {
message: 'The price is required and can\'t be empty'
},
regexp: {
regexp: /^\d+(,\d{1,2})?$/,
message: 'The price can only consist of digits or , to indicate fraction values'
}
}
}
});
};
function isFormValid(){
// Get plugin instance
var bootstrapValidator = $('#myForm').data('bootstrapValidator');
bootstrapValidator.validate();
// validate and then call method is Valid to check results
return bootstrapValidator.isValid();
};
您可以将以上代码封装在requireJS模块或JS名称空间中,甚至封装在角度服务中。 在您的控制器中,您可以调用“ isFormValid”来检查所有输入对于该特定形式是否正确:
/* callback for ng-click on your controller: */
$scope.saveRecord = function () {
// validate fields
if (isFormValid()) {
MyService.save($scope.record);
// ...
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.