-1

This is a ready-baked regex that I got from the internet just to see how regex works in JavaScript (and jQuery). Here is my script:

<script>
    $(document).ready(function(){
        var regexp = new RegExp(([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4}));
        $("#submit").click(function(){
            var result = regexp.test( $("#email").val() );
            if(result){
                $("form").submit();
            }else{
                alert("Invalid Email Address");
            }
        });
    });
</script>   

However, the form always submits despite entering a wrong email address.

I have read on how test() works. It know that it returns the right answer and then advances a pointer to the next value. So if it returns true, the pointer points to false. I do not see how that can be a problem here.

what is wrong here? :)

HTML:

<body>
    <center>
        <form name="subscription" method="post" action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi">
            <input type="text" name="email" size="30" id="email"></input>
            <button id="submit">Submit</button>
        </form>
    </center>
</body>
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
An SO User
  • 24,612
  • 35
  • 133
  • 221

6 Answers6

2

Your regex initialization should be string and it should be escaped.

var regexp = new RegExp("([\\w\\.-]+)@((?:[\\w]+\\.)+)([a-zA-Z]{2,4})");

You can also use:

var regexp = /([\w\.-]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/;
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
2

Use this instead?

<input type="email" />
MrProgram
  • 5,044
  • 13
  • 58
  • 98
2

You need to double escape your Regex. Try this-

var regexp = new RegExp("([\\w-\\.]+)@((?:[\\w]+\\.)+)([a-zA-Z]{2,4})");

Edit

It is always helpful to log the result so that you see if your regexp string is correct, eg:

console.log("([\\w-\\.]+)@((?:[\\w]+\\.)+)([a-zA-Z]{2,4})");
console.log("([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})");
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
0

write it a regex (note the /)

Regex: var regexp = new RegExp(/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/);

VeXii
  • 3,079
  • 1
  • 19
  • 25
0

In Html5, There is a new attribute type="email" is available.

Instead of using input type="text"

Please try this!

TELMILA
  • 83
  • 9
0

Please try like this:

var regex = /^[a-zA-Z0-9äöüÄÖÜ._-]+@[a-zA-Z0-9äöüÄÖÜ.-]+.[a-zA-Z]{2,4}$/;

TELMILA
  • 83
  • 9