mwc-textfield input pattern not working for backslash or vertical bar

48 Views Asked by At

I am trying to add a pattern to a mwc-textfield input to filter a file name. My pattern seems to be valid js regex and seems to work on a html input but does not as a pattern on a mwc-textfield. I have two problems:

  1. \| or \ gives Pattern attribute value ^[^|\/:*"<>]+$ is not a valid regular expression: ect... but \\| works which confuses me
  2. \\ never actually seems to match no matter what I try.

Example: https://codesandbox.io/p/sandbox/fervent-field-jjpvjz

Regex: ^[^\|\\\/:\*&quot;&lt;&gt;]+$

Can anyone explain this weirdness or what I'm doing wrong? Thanks!

1

There are 1 best solutions below

2
Augustine Kim On BEST ANSWER

Since you're writing the regex pattern within the JS tagged template string, you need to escape the \, so you should double it.

html`
      <mwc-textfield
        outlined
        validationMessage="WRONG!"
        pattern='^[^\\|\\\\\\/:*&quot;&lt;&gt;]+$'
        label="Test"
        value="Hello|"
      >
      </mwc-textfield>
    `