0

Because of a linting issue (line too long), I'm trying to break up a regex into two lines. Given the function

function isValidEmail(email) {
    const pattern = new RegExp(`/^(?!.*[._@]{2})[a-z0-9\u00C0-\u00D6\u00D9-\u00F6\u00F9-\u00FC][a-z0-9_.
\u00C0-\u00D6\u00D9-\u00F6\u00F9-\u00FC]*@\w+(\.\w+)?(\.[a-z]{2,3})?\.[a-z]{2,3}$/i`);
    return pattern.test(email.trim());
}

My solution was to use backticks, but it seems that converting a RegExp into a String isn't as straightforward as it seems in Javascript (to be clear, I'm writing typescript and having it transpiled to Javascript.) When I debug the resulting javascript file, the pattern variable becomes

/\/^(?!.*[._@]{2})[a-z0-9À-ÖÙ-öù-ü][a-z0-9_.
À-ÖÙ-öù-ü]*@w+(.w+)?(.[a-z]{2,3})?.[a-z]{2,3}$\/i/

I'm not sure what's happening the the RegExp, but I haven't been able to get my email RegExp to work aftre breaking it into multiple lines. What is happening in the background, and how do I solve for this?

Shwheelz
  • 545
  • 3
  • 8
  • 22
  • 1) When defining a regex in the constructor notation, never include regex delimiters, 2) In a constructor notation, ``\`` must be doubled to define a literal ``\``. – Wiktor Stribiżew Aug 27 '17 at 17:35
  • Just a thought: just use constraint validation? don't have to be that complicated... `elm = document.createElement('input'); elm.type = 'email'; elm.value = email; return elm.validity.valid;` or better yet, only trigger the method on `onsubmit` and not on `onclick` then the method will only run when all fields are valid, put `required` attribute on it if you want – Endless Aug 27 '17 at 17:37
  • When you start debating stylistic choices for your regular expressions because they're too long, I would reconsider using regex at all. Some real code, maybe even a proper parser, might be a better option. – ssube Aug 27 '17 at 17:47
  • @WiktorStribiżew still unable to get this to work. Can you be more clear about your first point perhaps? – Shwheelz Aug 27 '17 at 18:01
  • Remove `/` at the start / end of the pattern. – Wiktor Stribiżew Aug 27 '17 at 18:09
  • @WiktorStribiżew this mostly worked, but is there any way to maintain case insensitivity this way? If I remove the / at the end, it eventually gets turned into $i/ instead of $/i. I can remove the /i and it will work, but I lose case insensitivity. – Shwheelz Aug 27 '17 at 18:27
  • 1
    You are using a constructor notation. See [`RegExp` reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp): `new RegExp(pattern[, flags])`. E.g. `new RegExp("word", "ig")` - case insensitive and global. – Wiktor Stribiżew Aug 27 '17 at 18:30
  • Thanks!!! This was a big help! – Shwheelz Aug 29 '17 at 20:14

0 Answers0