HTML5输入模式中的无效正则表达式 [英] Invalid regular expression in HTML5 input pattern

查看:69
本文介绍了HTML5输入模式中的无效正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在HTML输入中使用此正则表达式(取自

I need to use this regular expression in a HTML input (taken from Regular expression for a list of items separated by comma or by comma and a space):

[^,\s][^\,]*[^,\s]*

所以我在输入中设置它:

So I set it in an input:

<input type="text" class="form-control" id="input" name="input" data-ng-model="myModel" pattern="[^,\s][^\,]*[^,\s]*">

但是我在控制台中收到此错误:

But I get this error in console:

Pattern attribute value [^,\s][^\,]*[^,\s]* is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /[^,\s][^\,]*[^,\s]*/: Invalid escape

该正则表达式有什么问题?

What is wrong with that regex?

我正在使用Angular 1.5 BTW.

I'm using Angular 1.5 BTW.

推荐答案

您需要删除逗号前的转义反斜杠并使用

You need to remove the escaping backslash from before the comma and use

 pattern="[^,\s][^,]*[^,\s]*"

由于FF和Chrome使用ES6 regex语法规范编译 pattern regex,并在编译RegExp对象时使用/u 修饰符,因此这是必要的.这对模式设置了某些限制.在这种情况下,在字符类中转义了常规符号而不是特殊的元字符(逗号).因此,消除转义即可解决问题.

It is necessary since FF and Chrome compile the pattern regex using the ES6 regex syntax specifications, and use the /u modifier when compiling the RegExp object. This lays certain restrictions on the pattern. In this case, a regular symbol, not a special metacharacter, a comma, was escaped inside a character class. Thus, removing the escape solves the issue.

input:valid {
  color: black;
  border: 5px solid #dadadada;
  border-radius: 7px;
}
input:invalid {
  color: navy;
  outline: none; 
  border-color: #ff1050;
  box-shadow: 0 0 10px #ff0000;
}

<form>
  <input type="text" class="form-control" id="input" name="input" data-ng-model="myModel" pattern="[^,\s][^,]*[^,\s]*">
</form>

这篇关于HTML5输入模式中的无效正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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