我怎么能简化表单验证? [英] How can I simplify form validation?
本文介绍了我怎么能简化表单验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下code似乎工作pretty好做基本要求表单验证。
The code below seems to work pretty well for doing basic required form validation.
该表单显示一个红色的姓名为必填项的时候现场脏+无效,消息的大!的如果字段是消息脏+有效。
The form displays a red Name is required message when the field is dirty + invalid and a Great! message if the field is dirty + valid.
但它是有重复的形式是code的每一个领域一个烂摊子:
But it's a mess having repeat this code for each and every field in the form:
<form name="myForm">
<div class="control-group"
ng-class="{error: myForm.name.$invalid && myForm.name.$dirty}">
<label>Name:</label>
<input type="text" name="name" ng-model="user.name" required/>
<span ng-show="myForm.name.$invalid && myForm.name.$dirty"
class="help-inline">Name is required</span>
<span ng-show="myForm.names.$valid && myForm.names.$dirty">Great!</span>
</div>
</form>
我希望能够指定 NG-节目
和纳克级
属性在一些更简单的方法
I would like to be able to specify the ng-show
and ng-class
attributes in some easier way.
推荐答案
您可以做到这一点的方法之一是抽象您的验证前pression到范围的方法:
One way you could do it is to abstract your validation expression to scope methods:
<大骨节病> PLUNKER 大骨节病>
<div class="control-group" ng-class="{error: isInvalid('name')}">
<label>Name:</label>
<input type="text" name="name" placeholder="Name" ng-model="user.name" required/>
<span ng-show="isInvalid('name')" class="help-inline">Name is required</span>
<span ng-show="isValid('name')">Great!</span>
</div>
控制器
function Ctrl($scope) {
$scope.isInvalid = function(field){
return $scope.myForm[field].$invalid && $scope.myForm[field].$dirty;
};
$scope.isValid = function(field){
return $scope.myForm[field].$valid && $scope.myForm[field].$dirty;
};
}
这篇关于我怎么能简化表单验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文