Combine ng-pattern and ng-if

I implemented a validation pattern directive, that only gets validated if ng-required="true". Usage: <input ng-required="isRequired()" ng-pattern-if-required="myPattern" name="myName"> The directive: angular.module('directives') .directive('ngPatternIfRequired', ['underscore', function (_) { return { restrict: 'A', require: 'ngModel', link: function (scope, elem, attrs, ctrl) { var required = true; var pattern = attrs.ngPatternIfRequired; if (_.isNull(pattern) || _.isUndefined(pattern)) { throw 'regular expression in ngPatternIfRequired is undefined'; } var re = new RegExp(pattern.substring(1, pattern.length - 1)); var validate = function() { var pass = false; if (_....

February 25, 2016 · 2 min · Markus Ruepp