10

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.

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@ Jonatas Walker - worked perfectly. How does it work?
Inside test function make your conditionals. Return a boolean for your validation.
i dont wanna make function i wanna do this in html but it is not working can you provide answer for using this in html
11

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

ng-pattern="condition ? '[A-Za-z0-9_-]{1,60}' : ''"

2 Comments

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 jsfiddle.net/9bua4k2d/1
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.