-3

I am able to check for empty field but how do I also check for the valid email checking regular expression? here is what I have so far

<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
var y=document.forms["myForm"]["email"].value;
if (y==null || y=="")
  {
  alert("email must be filled out");
  return false;
  }
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname"><br>
email: <input type="text" name="email">

<br><br>
<input type="submit" value="Submit">
</form>
soum
  • 1,131
  • 3
  • 20
  • 47

2 Answers2

1

The fist thing you could do is use the HTML5 type="email" attribute., the browser will validate natively. But you must always have a fall-back.

Use (found here)

/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/

as regualar expression: and do

var validEmailStyle = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
if(!validEmailStyle.test(document.forms["myForm"]["email"].value))
{
  // the user is dumb and fill in an invalid email, show a help text
  // or something like that
}​

- edit after valid comment of PeeHaa

You must not forget to also validate server side, if you are using PHP you can use preg_match with the same regexp

Community
  • 1
  • 1
beardhatcode
  • 4,533
  • 1
  • 16
  • 29
-1
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i

if(!pattern.test(userinput))
{
  alert('not a valid e-mail address');
}​

Just showing an example, you can find a better regex pattern.

Kolby
  • 2,775
  • 3
  • 25
  • 44
  • Why are people hating my mailaddresses? :( – PeeHaa Feb 05 '13 at 20:13
  • The `+` symbol is valid in the alias part of an address. Also, domains with more than two dot-separated names will be regarded as invalid by this regex, so this would reject my `me@domain.me.uk` address. Even '.com' domains often have more than two parts. – halfer Feb 05 '13 at 20:29
  • Also there is a lot more when it comes to valid emailaddresses. For an example of a decent regex see PHP's regex to validate them: http://stackoverflow.com/questions/12026842/how-to-validate-an-email-address-in-php/12026863#12026863 – PeeHaa Feb 06 '13 at 08:46