简体   繁体   中英

Unexpected validation behavior in Angular using ng-pattern

I'm experiencing some weird validation behavior using Angular's built-in form validator. On my username <input> field, I have a ng-pattern that allows only letters or numbers ( ng-pattern="/[A-Z0-9]/i" ).

But the validation doesn't work the way I expect it to. For example, it recognizes the username input is invalid when I type in a bunch of symbols eg !@#$ . But if I start off with a few letters and then type in a bunch of symbols, such as SomeUser!@#$ , it will throw a validation error on the first symbol, ! , but when I type in the second symbol @ , it turns the error back off. Every 3rd or 4th symbol I type in it will toggle on/off the error again.

I've tried looking at the Angular docs but I don't see anything that indicates I'm implementing ng-pattern incorrectly.

Here is the code:

<form name="signupForm" ng-submit='signup()'>
    <input name="nameInput" type='text' ng-model='user.username' ng-pattern = "/[A-Z0-9]/i">
    <input name="passwordInput" type="password" ng-model='user.password' ng-pattern = "/[A-Z0-9]/i">
    <button>signup</button>
</form>
<span class = 'error' ng-show="signupForm.nameInput.$invalid && signupForm.nameInput.$dirty">Invalid username</span>

I think this is what you need:

<input name="nameInput" type='text' ng-model='user.username' ng-pattern="/^[A-Z0-9]*$/i">

The Angular documentation explicitly states that you should not use the g flag.

The asterisk in the regexp means 'zero or more', so the empty string will be regarded as valid. You could use '+' instead ('one or more'), but this implies that the error message will appear right away, when the user hasn't typed anything in the input field yet. You could use ng-required instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM