Reputation: 2175
Hi I am developing web application in angularjs. I have requirement to validate textbox. It should accept only numbers with max 10 digits. I have directive but current directive should not restrict number of digits typed.
myapp.directive('validNumber', function () {
return {
require: '?ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function (val) {
if (angular.isUndefined(val)) {
var val = '';
}
var clean = val.replace(/[^0-9]+/g, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function (event) {
if (event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
<div class="inputblock" ng-class="{ 'has-error' : ((form1.$submitted && form1.idnumber.$invalid )|| (form1.idnumber.$invalid && form1.idnumber.$dirty))}">
<label class="inputblock-label" ng-show="idnumber">{{ 'ID Number' | translate }}</label>
<span class="ang-error" style="color:#fff" ng-show="form1.idnumber.$dirty && form1.idnumber.$invalid ">
<span ng-show="form1.idnumber.$invalid && form1.idnumber.$dirty">*{{'Max allowed digits 10' | translate}}</span>
</span>
<input class="with-icon" type="text" name="idnumber" placeholder="{{ 'ID Number' | translate }}" ng-model="idnumber" required ng-pattern="/^[0-9]{1,7}$/" > <!--valid-number-->
</div>
May i know what should be changed in the above directive so that it can accept maximum only 10 digits! Any help would be appreciated. Thank you.
Upvotes: 0
Views: 542
Reputation: 2550
Use the following code and try. my original purpose of this code was to limit the number to integer. But I have modified it a little so you can use this
(function() {
'use strict';
angular.module('app').directive('intValidate', intValidate);
function intValidate($locale) {
var decimalSep = $locale.NUMBER_FORMATS.DECIMAL_SEP;
var toNumberRegex = new RegExp('[^0-9\\' + decimalSep + ']', 'g');
function toNumber(currencyStr) {
return parseFloat(currencyStr.toString().replace(toNumberRegex, ''), 10);
}
return {
restrict : 'A',
require : 'ngModel',
link : function validate(scope, elem, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(newViewValue) {
var modelValue = toNumber(newViewValue);
var valid = modelValue <= 9999999999;
modelCtrl.$setValidity('limitcheck', valid);
return valid ? newViewValue : undefined;
});
}
};
}
})();
and use,
<input type="text" id="value" name="value" int-validate>
and if you want an error message
<p class="help-block" ng-if="cacc.form.value.$error.limitcheck">Max 10 digits allowed</p>
Upvotes: 1