Narek Mamikonyan Narek Mamikonyan - 3 months ago 26
AngularJS Question

Angular directive: Validate value before binding it to model

Is there a way to not bind value to model , and ONLY bind it to model when value is valid.


Use $parsers. The example below restricts input to your model for numbers only. Obviously you can change that to be whatever you require to make your input valid.

directive('onlyDigits', function () {

    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                if (inputValue == undefined) return '';
                var transformedInput = inputValue.replace(/[^0-9]/g, '');
                if (transformedInput !== inputValue) {
                return transformedInput;

<input type="text" name="number" only-digits>

Code sample comes from this SO question