K
K
KononovD2019-11-16 23:34:06
JavaScript
KononovD, 2019-11-16 23:34:06

How to pass a regular expression to the pattern attribute of an input?

Good evening, I have an input component. This class has a field with all the regular expressions I need:

regexp = {
    username: /^[a-zа-я0-9_-]{2,16}$/,
    password: /^.{6,18}$/,
    email: /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
    noRegexp: /./
  }

then I take these regular expressions and insert them into the pattern attribute of the input:
<input
          ...={ ... }
          pattern={ this.regexp[regexpName].toString().replace( /\//g, '' ) }
          ...={ ... }
        />

As far as I understand, pattern accepts a string, not a regular expression. from here .toString(), and then at random it turned out that with backslashes, the first and last, regulars do not work (the field always gives an error), from here .replace( /\//g, '' )
And so I want to know how what if I have backslashes in the regular expression itself? Maybe write a regular expression that will remove only the first and last slashes?
Tell.
Thanks

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
0
0xD34F, 2019-11-16
@KononovD

Maybe write a regular expression that will remove only the first and last slashes?

Why are regular expressions here? You know that the first and last characters in a line are superfluous - well, maybe cut them off?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question