9

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.

Hacker
  • 7,798
  • 19
  • 84
  • 154

2 Answers2

19

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.

Community
  • 1
  • 1
Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82
11

The following worked for me (AngularJS v1.5.11):

ng-pattern="condition ? '[A-Za-z0-9_-]{1,60}' : ''"
Tsvetan Ganev
  • 8,246
  • 4
  • 26
  • 43
Mathieu Allain
  • 339
  • 1
  • 4
  • 13
  • Do you have a JSFiddle for this? I can't get it to work with this version of AngularJS. here is an example to set a pattern for multiple of 25 http://jsfiddle.net/9bua4k2d/1/ – darudude Feb 03 '19 at 18:48
  • this doesnt seem to work with the latest version on Angular 7/8 `patterm="condition ? '[A-Za-z0-9_-]{1,60}' : ''` Do you know of any good solutions – Flash Oct 16 '19 at 13:04