【发布时间】:2016-11-10 04:56:39
【问题描述】:
我为 validate nic no 创建了如下指令
CustomerCompanyApp.directive('nicOnly', function () {
return {
restrict: "A",
require: 'ngModel',
link: function (scope, elem, attrs, modelCtrl) {
var limit = parseInt(attrs.nicOnly);
elem.bind('keypress', function (e) {
//console.log(e.charCode);
if (elem[0].value.length >= limit) {
if (e.charCode != 0) {
//console.log(e.charCode);
e.preventDefault();
return false;
}
} else {
if (elem[0].value.length == limit - 1) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/^[X|x|V|v]$/, '') : null;
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
} else {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d]/g, '') : null;
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
}
});
}
};
});
在 chtml 中
<div class="form-group">
<label class="control-label" for="customerNicNoforconfirmation">National identity card no</label>
<input class="form-control" type="text" name="customerNicNoforconfirmation" id="customerNicNoforconfirmation1" ng-model="customerNicNoforconfirmation" required="" nic-only="10">
<p ng-show="NicDetailsform.customerNicNoforconfirmation.$invalid && !NicDetailsform.customerNicNoforconfirmation.$pristine" class="danger">Customer Nic Required.</p>
</div>
上面的指令可以限制长度,只输入数字。 但现在我想将此验证添加到我的指令中,
- 输入的前 9 个字符必须是数字。
- 输入的最后 1 个字符必须是 V v X x 字母。
- 整个输入的长度必须是 10
在我的指令中,它可以将整个输入长度限制为 10,并且所有输入都只是数字。我找不到克服其他要求的方法。
【问题讨论】:
标签: javascript angularjs regex asp.net-mvc model-view-controller