0

Please see the code below:

function (string regex, string value)
{
    var regularExpression = new RegExp(regex); 
    return regularExpression.test(value);
}

Why does it fail? It seems to fail for everything I enter. I got the code from here: How to validate an email address in JavaScript? i.e. the community answer that starts: "I've slightly modified Jaymon's answer".

w0051977
  • 15,099
  • 32
  • 152
  • 329
  • 2
    Don't ever use `new RegExp` unless you need to create a regex dynamically, use a literal instead – CertainPerformance Apr 22 '19 at 10:04
  • @CertainPerformance , how would I cast a string to a regular expression? – w0051977 Apr 22 '19 at 10:08
  • As you're doing in this question, but you really shouldn't - like I said, use literals instead (here you have many unnecessarily escaped characters) – CertainPerformance Apr 22 '19 at 10:09
  • @CertainPerformance, please see my question now. Do you see why I need regex or is it still unnecessary? Thanks. – w0051977 Apr 22 '19 at 10:13
  • So you do need to create the regex dynamically - OK, see the linked canonical, you need to double-escape the backslashes – CertainPerformance Apr 22 '19 at 10:15
  • Thanks, however that link does not show how to double escape the backslashes. I have tried this: regex.replace("\", "\\"); – w0051977 Apr 22 '19 at 10:27
  • They need to be double-escaped in the original string, before it's passed to the function. You could also use [`String.raw`](https://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped/55793086#55793086) – CertainPerformance Apr 22 '19 at 10:43
  • Can I use string.raw in visual studio? I just see lots of errors with this string. Cannot believe how difficult this is. Thanks again. – w0051977 Apr 22 '19 at 10:46
  • I'd hope so - it's an ES2015 feature, which was ages ago, and code should probably be written in ESNext regardless, for ease of development. Your development environment should support it, but obsolete browsers may not, in which case you should (as always) use Babel to transpile the code to ES5 for production before serving to them – CertainPerformance Apr 22 '19 at 10:49

1 Answers1

-1

Try this

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[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,}))$/;
    return re.test(String(email).toLowerCase());
}