首页 > 代码库 > angular js input校验只能输入数字和字母 directive写法一则

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写法一则