Conditional ng-pattern in angular js

Hacker picture Hacker · Nov 20, 2015 · Viewed 13.1k times · Source

Is there a way to achieve conditional ng-pattern in angularjs

ng-pattern="(myForm.exipration.$dirty ? ('/^\d{2}[/]\d{4}$/') : '')"

i tried like above, but does not help.

Answer

Jonatas Walker picture Jonatas Walker · Nov 20, 2015

Markup

<input ... ng-pattern="handlePatternPassword">

Controller

$scope.handlePatternPassword = (function() {
  var regex = /^[A-Za-z0-9!@#$%^&*()_]{4,20}$/;
  return {
    test: function(value) {
      if ($scope.user.isLogged) {
        return (value.length > 0) ? regex.test(value) : true;
      } else {
        return regex.test(value);
      }
    }
  };
})();

From https://stackoverflow.com/a/18984874/4640499.