AngularJS: Dynamic Validation Directive

Standard

Custom directive that allows text only, number only, special character only or allow everything as per user choice.

Github Link

Angular Code:

(function () {
    'use strict';

    angular
        .module('sampleApp')
        .directive('validate', validate);

    function validate() {
        var directive = {
            restrict: 'EA',
            scope: {
                regex: '=criteria'
            },
            require: 'ngModel',
            controller: validateController,
            link: validateLink
        };

        return directive;
    }

    validateController.$inject = ['$scope'];

    function validateController($scope) {
    }

    function validateLink(scope, element, attrs, ngModelCtrl) {

        element.on('focus', function (e) {
            ngModelCtrl.$parsers.push(validateInput);
        });

        function validateInput(input) {
            if (input) {
                var regex = new RegExp(scope.regex);
                var newValue = input.replace(regex, '');
                if (newValue !== input) {
                    ngModelCtrl.$setViewValue(newValue);
                    ngModelCtrl.$render();
                }
                return newValue;
            }
            return undefined;
        }
    }

})();

Output:

2016-07-01 14_07_02-mozilla firefox

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s