角正则表达式测试输入不一致ng模式验证 [英] Angular regex test not consistent ng-pattern validation on input

查看:86
本文介绍了角正则表达式测试输入不一致ng模式验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对输入内容进行了ng-pattern验证

I have a ng-pattern validation on my input

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

这并非每次都起作用.并显示出非常奇怪的行为.

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

请参见 plnkr

我键入的第二个字符仅显示ngMessage.但是控制台会正确评估正则表达式测试.

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

我在angular的浏览器开发工具中设置了一个断点,用于测试正则表达式并在控制台中进行了一些调试.这是我的调试中的控制台输出.当我使用控制台时,调试器没有移动,因此未更改任何值. (->代表我的输入,<-是调试器吐出的内容)

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

有人可以告诉我怎么回事吗?请注意,regexp.test(viewvalue)首先是假的,然后在最后一个测试中才是真,而没有任何更改.

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.

推荐答案

您必须从正则表达式中删除/g,请参见更新了plunkr .

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

根据文档:

注意:避免在RegExp上使用g标志,因为它会导致每个连续的搜索都从上次搜索的匹配项的索引处开始,因此不会考虑整个输入值

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.

这篇关于角正则表达式测试输入不一致ng模式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆