angular js input校验只能输入数字和字母 directive写法一则
Posted braveliu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了angular js input校验只能输入数字和字母 directive写法一则相关的知识,希望对你有一定的参考价值。
js代码:
.directive(‘validateNumberLetter‘, function () {
return {
require: ‘ngModel‘,
link: function (scope, elm, attrs, ctrl) {
scope.$watch(attrs.ngModel, function(n){
if(!n) return;
var oldName = attrs.validateNumberLetter;
if(oldName !== n){
var reg=/[^A-Za-z0-9]/;
if (n.length) {
if(reg.test(n)){
// it is invalid, return undefined (no model update)
ctrl.$setValidity(‘validateNumberLetter‘, false);
return undefined;
}else{
// it is valid
ctrl.$setValidity(‘validateNumberLetter‘, true);
return n;
}
}
}
});
}
};
})
html代码:
<div class="form-group-right">
<input required validate-number-letter
id="name"
name="name"
class="form-control verify-input"
type="text"
ng-model="volume.name"
ng-maxlength="255"
ng-disabled="context.mode === ‘extend‘ ||
context.mode === ‘attach‘ ||
context.mode === ‘detach‘"
placeholder="{% trans ‘enter a volume name‘ %}"/>
<p class="help-block alert-fixed alert-danger"
ng-show="form.name.$error.required && form.name.$dirty">
{% trans "A volume name is required." %}
</p>
<p class="help-block alert-fixed alert-danger"
ng-show="form.name.$error.maxlength && form.name.$dirty">
{% trans "Name length should be less than 255 chars." %}
</p>
<p class="help-block alert-fixed alert-danger"
ng-show="form.name.$error.validateNumberLetter && form.name.$dirty">
{% trans "should be letter" %}
</p>
</div>
以上是关于angular js input校验只能输入数字和字母 directive写法一则的主要内容,如果未能解决你的问题,请参考以下文章
angularjs中的验证input输入框只能输入数字和小数点