1

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 e.g. !@#$. 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>
2
  • 1
    "I have a ng-pattern that allows only letters or numbers" - No. You have a pattern that allows anything as long as there is one letter or number in it. You only get an error message once in a while because the \g flag lets the next check start at the last match instead of the beginning of the string. Commented Nov 7, 2015 at 22:02
  • Yup, my regexp was incorrect. Thanks! Commented Nov 7, 2015 at 22:28

1 Answer 1

1

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.

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

2 Comments

I guess /i modifier is allowed.
Yes, sure, I have added the /i to my answer. Thanks!

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.