2

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?

I'm using Angular 1.5 BTW.

Community
  • 1
  • 1
Potray
  • 1,928
  • 16
  • 23

1 Answers1

3

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

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

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>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563