0

I found a regex at regexlib and I want to use it in a simple string validation using javascript.

The regex is:

^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$

But I tried to use it like this:

mystring = '[email protected]';
re = '^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$';

    if(mystring.match(re)){
     console.log('true');
    }

And I got this console error:

Uncaught SyntaxError: Invalid regular expression: //^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$/: Range out of order in character class

What's wrong? I'm not a professional.. This is just a simple project I'm trying to do in my free time.

2
  • Possible duplicate of Range out of order in character class in javascript Commented Apr 30, 2018 at 2:29
  • When I 'try to follow this another post solution I get another error: Uncaught SyntaxError: Invalid or unexpected token Commented Apr 30, 2018 at 2:33

2 Answers 2

3

Try doing it like this:

var re = new RegExp('^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$');

In javascript the \ character escapes the string so that's why it's not working. In the previous example I just doubled them up and that should work. Here it is in practice:

mystring = '[email protected]';
re = new RegExp('^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$');

if (mystring.match(re)) {
  console.log('true');
}

You could also try a RegEx literal like this:

var re = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

Here is that in practice:

var mystring = '[email protected]';
var re = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

if (mystring.match(re)) {
  console.log('true');
}

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

Comments

2

To define a RegEx you need to use / and not '.

mystring = '[email protected]';
re = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    if(mystring.match(re)){
     console.log('true');
    }

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.