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.

1
  • 1
    Invalid escape before "," Commented Mar 28, 2017 at 13:53

1 Answer 1

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>

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

Comments

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.