-1

I apologize in advance - this should be something really simple and for some reason I can't get it to work correctly (I'm new to javascript!). I'm trying to do some client-side javascript validation (I will also server-side validation) but it doesn't work as hoped!

I know about Validate email address in Javascript? but for some reason, I can't get it to work in my code. Here is the if statement (it's part of a couple of things that happen on a button press):

var signUpEmail = document.getElementById('signUpEmail');
var emailVerification = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

//Validates email address
if (emailVerification.test(signUpEmail) == false) {
    alert("Please enter a valid email address");
    return false;
};

Every time I press the button with anything (even a correct email) in the field, the alert displays.

Community
  • 1
  • 1
Kody R.
  • 2,430
  • 5
  • 22
  • 42
  • If you're going to validate on the server anyway, why not just use the inbuilt validation which will cover most current browsers (e.g. ``, ``). – Marty Feb 15 '16 at 22:45
  • 4
    If you want to get value of a text field, you have to get its `value` property, like that: `document.getElementById('signUpEmail').value`. – Michał Perłakowski Feb 15 '16 at 22:46
  • 1
    I've used the regex `/^[^@]+@[^@]+\.[^@]+$/` for more of a sanity check than anything else, since there are so many different valid emails. yours for instance would fail with the valid foo+bar@gmail.com – Plato Feb 15 '16 at 22:52
  • @Gothdo that was definitely it. I put it inside my if statement as if (emailVerification.test(signUpEmail.value) == false) – Kody R. Feb 15 '16 at 22:55

1 Answers1

2

You are passing the element to regular expression change it like following

var signUpEmail = document.getElementById('signUpEmail').value;
Nadeem Manzoor
  • 760
  • 5
  • 14