angular js directive for decimal number





Here you find a directive for angular js. input will be a valid decimal number. It will prompt your for spaces too.

 
app.directive('validNumberdecimal', function () {
return {
require: 'ngModel',
link: function (scope, el, attrs, ngModel) {
el.bind('change', function () {
scope.$apply(function () {
ngModel.$setViewValue(el.val());
ngModel.$render();
 
var number = el[0].value;
 
var re = /^[0-9]+(\.[0-9]{1,2})?$/;
 
if (!re.test(number)) {
ngModel.$setValidity("number", false);
}
else {
ngModel.$setValidity("number", true);
}
})
})
}
}
})

Html Input

<input type="text" ng-model="myNumber" name="myNumber"  step="0.01" valid-numberdecimal required />

Validation message

<div ng-show="myNumber.$dirty && myNumber.$error.number" class="errorMessage">
                               Number is not a valid decimal number.
                            </div>



Tags: , ,

Comments are closed.