0

Javascript Regex Error

As you can see, the e-mail should be valid. Regardless of what I enter, z returns null. Am I using the wrong syntax, entirely?

How do I make this regex return true? Thanks!

function emailValidate() {
var x = document.forms["creation"]["emailCreation"].value;
var y = x.length;
var z = x.match(" /^(([^<>()[\]\\.,;:\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,}))$/");
var_dump(z);
var_dump(x);
icor103
  • 193
  • 1
  • 8
  • 1
    i think you need to remove the double quotes in `x.match()` – Avinash Raj Oct 18 '14 at 06:19
  • Anivash - that worked, partially. It turned z into an array, and if (z == true) { } does not work, the same for != or !== NULL. Any more advice? Thanks! – icor103 Oct 18 '14 at 06:24
  • Your regex works. Show the code that doesn't work. –  Oct 18 '14 at 06:28
  • dan111: `if (z !== NULL) { document.getElementById("here").innerHTML = "test7"; }` --- I also used `!= NULL`, and `== true` – icor103 Oct 18 '14 at 06:33

2 Answers2

1

If you are not actually wanting to get matches and are just wanting to test that the email fits the regular express than use the test method of the RegExp object and pass the string you want to test against.

var emailReg = /^(([^<>()[\]\\.,;:\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,}))$/;

function emailValidate() {
    var x = document.forms["creation"]["emailCreation"].value;
    var y = x.length;
    var z = emailReg.test(x);
    alert(z);
    return z;
}
<form name="creation" onsubmit="return emailValidate()">
   <input name="emailCreation" type="email" />
   <input type="submit" />
</form>
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
0

Your Regex is valid according to my test here: http://regexr.com/39on5

The issue I see is that the .match() method should takes a Regex. You have passed a Regex inside a string.

The solution is to destringify (takes the quotes off the beginning and end):

var z = x.match(/^(([^<>()[\]\\.,;:\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,}))$/);

This will return an array of matches, per MDN:

["admin@website.com", "admin", "admin", undefined, undefined, "website.com", undefined, "website.com", "website."]

How you want to further validate using this array is up to you. Here is a suggestion on Stack Overflow. Hope that helps!

Community
  • 1
  • 1
Adam
  • 2,027
  • 1
  • 16
  • 27
  • PS, I didn't address it because it wasn't part of your core question, but is there are reason you're using var_dump? This doesn't exist in JavaScript, which has its own garbage collection. – Adam Oct 18 '14 at 06:38
  • Adam, yes: If you're refering to console.file(?), it's a massive pain to use. I found a script that mimics var_dump, and added that for testing. :) – icor103 Oct 18 '14 at 06:48