Page 56 - AngularJS权威教程
P. 56
36 第 7 章 过滤器
Your username is required to be at least 3 characters
</small>
<small class="error"
ng-show="signup_form.username.$error.maxlength">
Your username cannot be longer than 20 characters
</small>
<small class="error"
ng-show="signup_form.username.$error.unique">
That username is taken, please try another
</small>
</div>
</div>
在最后一个输入字段中除了同前面相同的验证外,还添加了一个自定义验证。这个自定义验
证是用AngularJS指令定义的:
app.directive('ensureUnique', function($http) {
return {
require: 'ngModel',
link: function(scope, ele, attrs, c) {
scope.$watch(attrs.ngModel, function(n) {
if (!n) return;
$http({
method: 'POST',
url: '/api/check/' + attrs.ensureUnique,
data: {
field: attrs.ensureUnique,
value: scope.ngModel
}
}).success(function(data) {
c.$setValidity('unique', data.isUnique);
}).error(function(data) {
c.$setValidity('unique', false);
});
});
}
};
});
当表单内容通过验证后,会向/api/check/username发送一个POST请求来验证用户名是否可用。
显然由于我们一直在讨论前端的代码,现在并没有可以用来测试这些内容的后端,尽管实现这个
后端并不复杂。
最后,把按钮放进去。可以用ng-disabled指令基于表单的合法性来启用或禁用按钮:
<button type="submit"
ng-disabled="signup_form.$invalid"
class="button radius">Submit</button>
在线示例:http://jsbin.com/ePomUnI/5/edit。
之前提到过,表单本身会提供$invalid和$valid属性。
尽管实时验证非常有用,但是当用户还没有完成输入时就弹出一个错误提示,这种体验是非
常糟糕的。应该在用户提交表单或完成当前字段中的输入后,再提示验证信息,这样才是用户友
好的。下面看看如何实现这两种效果。