angularjs 通过自定义指令(directive) 可以实现对输入框的校验,只允许输入字母,数字。
代码如下:
// 自定义指令。用户名输入限制
app.directive('checkUsername', function(){
return{
require: 'ngModel',
link: function(scope, ele, attrs, c){
scope.$watch(attrs.ngModel, function(n){
if(!n || n == '') return;
c.$setValidity('checkUsername', /^[0-9a-zA-Z]+$/.test(n));
});
}
}
});
使用:
<label class="item item-input item-stacked-label">
<span class="input-label">用户名</span>
<input type="text" placeholder="用户名(字母/数字)" name="username" ng-model="user.username" required check-username>
<span style="color:red" ng-show="regist_form.username.$error.checkUsername">
<span ng-show="regist_form.username.$error.checkUsername">必须为字母/数字</span>
</span>
</label>