2

I have a ng-pattern validation on my input

ng-pattern="/^(.+)$/g"

This does not work the same everytime. And shows very weird behaviour.

See plnkr

The ngMessage is only shown on every second character I type. But the console evaluates the regex test correctly.

I set a breakpoint in the browser dev tool on the line in angular that tests the regex and did some debugging in the console. Here is the console output from my debugging. The debugger did not move while I was using the console so no values had been changed. (-> represents my input, <- is what the debugger spits out)

-> regexp.test(viewValue)
<- false

-> regexp
<- /^(.+)$/g

-> /^(.+)$/g.test(viewValue)
<- true

-> regexp.test(viewValue)
<- true

Can someone tell me what is going on? Note how regexp.test(viewvalue) was false first, then was true on the last test without anything changing.

2
  • Just remove global modifier g. It works as expected. plnkr.co/edit/FZPFvHp8qkKqgy3oD7Er?p=preview Commented Nov 17, 2016 at 7:19
  • @StepanKasyanenko Shouldn't the regex match and display the message if more then one character is in the textbox? Commented Nov 17, 2016 at 22:57

1 Answer 1

3

You must remove the /g from the regex, see updated plunkr.

According to the docs:

Note: Avoid using the g flag on the RegExp, as it will cause each successive search to start at the index of the last search's match, thus not taking the whole input value into account.

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

6 Comments

But now the message doesn't display at all. I should get a match if there is more than 1 character in the text box?
When do you need the error message to appear? ^.+$ means there must be 1+ chars in the text field. So, when you type characters, the regex matches the input, and no error message appears.
Yup, but no error is showing if I type anything in the textbox in your updated plunkr?
Right, because the /^.+$/ regex matches any string with 1+ chars. Under what conditions do you want the error message to be shown? Have you got any requirements for the regex?
This is a funny requirement, I have been here for more than 2 years, it is the first time I hear of such a regex need. Use ng-pattern="/^$/" to match an empty string. An error will apprear when there is anything typed into the text field. Do not forget to add ng-trim="false" to the input element to disallow whitespaces only. See this plunkr.
|

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.