我需要在 HTML 输入中使用此正则表达式(取自 Regular expression for a list of items separated by comma or by comma and a space ):
[^,\s][^\,]*[^,\s]*
所以我将其设置在输入中:
<input type="text" class="form-control" id="input" name="input" data-ng-model="myModel" pattern="[^,\s][^\,]*[^,\s]*">
但是我在控制台中收到此错误:
Pattern attribute value [^,\s][^\,]*[^,\s]* is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /[^,\s][^\,]*[^,\s]*/: Invalid escape
该正则表达式有什么问题?
顺便说一句,我正在使用 Angular 1.5。
最佳答案
您需要删除逗号之前的转义反斜杠并使用
pattern="[^,\s][^,]*[^,\s]*"
这是必要的,因为FF和Chrome使用ES6正则表达式语法规范编译pattern
正则表达式,并在编译RegExp对象时使用/u
修饰符。这对模式有一定的限制。在这种情况下,在字符类中转义了常规符号,而不是特殊的元字符(逗号)。因此,删除转义可以解决问题。
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>
关于javascript - HTML5 输入模式中的正则表达式无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43071450/