-4

I'm having trouble validating email addresses with JS. Here is my code:

var regEmail = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/i;
var result = regEmail.test('username');
alert(result);

So no matter what kind of email address I type, it always shows "false". I copied the regex expression from somewhere on stackoverflow, but I think it should actuylly work...

EDIT

$(document).ready(function() {

        $('#submitBtn').click(function() {

        //Überprüfe ob der Benutzername leer ist
        var username = $('#username').val();
        if (username == ""){
            alert ("User name cannot be empty!");
        }

        //Email validation

        var regEmail = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/i;
        var result = regEmail.test('username@example.com');
        alert(result);

        });
    });
milami
  • 39
  • 1
  • 6
  • 4
    This returns true: [`var result = regEmail.test('username@example.com');`](http://jsfiddle.net/pjLkncpw/). – Wiktor Stribiżew Sep 15 '15 at 09:11
  • 2
    Like almost every other regex for email validation, that one disallows perfectly valid addresses. Validation beyond "is there at least one character either side of an `@`?" is usually a waste of time. Send to the address, have the user verify they got the message. – T.J. Crowder Sep 15 '15 at 09:14
  • I just tested it... it shows false... – milami Sep 15 '15 at 09:15
  • 1
    @alina: *"I just tested it... it shows false"* No, it doesn't: http://jsfiddle.net/ygd1y1at/ – T.J. Crowder Sep 15 '15 at 09:16
  • then what the hell is wrong with my code... I just tested it (I made a form) and it shows "false" all the time... I must be doing something wrong, I just dont know what – milami Sep 15 '15 at 09:19
  • @alina, post complete code, obviously - problem is somewhere else... – sinisake Sep 15 '15 at 09:20
  • You are probably using wrong selector for email field. Re-check your HTML.... or, post your form html here.... http://jsfiddle.net/nkk1k084/ it works fine.... – sinisake Sep 15 '15 at 09:29
  • @nevermind thanks, I'll do that :) – milami Sep 15 '15 at 09:30

1 Answers1

-2

The regex validates against A-to-z|A-to-Z|0-9 followed by @ symbol and A-to-z|A-to-Z|0-9 followed by dot and two to four letter of A-to-z|A-to-Z|0-9

You're passing only a single string without matching the regex rules.

slashsharp
  • 2,823
  • 2
  • 19
  • 26