Angular ng-pattern does not check the upper limit of the characters of my regular expressions

I am just starting to test the ng template with some regular expressions that I used in Angular projects and it worked fine. But using ng-pattern, they don't seem to work. For example, I have this regular expression that successfully validates a string of 6-20 characters with at least one alphanumeric character and 1 numeric character:

"^.*(?=.{6,20})(?=.*\d)(?=.*[a-zA-Z]).*$" 

However, in my Angular example, it checks everything successfully, except that it does not start when the string goes beyond 20 characters:

 <div class="controls"> <input type="text" ng-model="user.Password" id="Password" name="Password" title="Password" required ng-pattern="^/.*(?=.{6,20})(?=.*\d)(?=.*[a-zA-Z]).*$/" /> <span ng-show="form.Password.$dirty && form.Password.$error.required">{{'_PasswordRequired_' | i18n}}</span> <span ng-show="form.Password.$dirty && form.Password.$error.pattern">{{'_PasswordLengthAndAlphanumeric_' | i18n}}</span> </div> 

Is there some kind of syntax error, or is there some other reason this doesn't work?

+4
source share
1 answer

You miss the end anchor and you have one .* Too much (at the beginning):

 ^ # Start of string .* # Match *any* number of characters (?=.{6,20}) # *Then* check that 6-20 characters follow <snip> .* # *Then* match any number of characters anyway $ # until the end of the string 

This will work:

 "^(?=.{6,20}$)(?=.*\d)(?=.*[a-zA-Z]).*$" 

But it would be easier (and more obvious) to do a length check outside of the lookahead anyway:

 "^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$" 

(which in turn leads me to ask why you impose such a low upper limit? My passwords generated by KeePass usually have a length of at least 30 characters)

+5
source

Source: https://habr.com/ru/post/1491092/


All Articles