0

I have been trying to use this regex for email in javascript but i can not seem to find one that actually works! I just need to take out all special characters that would not be needed for an email address (< > ? / | [ ] { } ( ) * & ^ % $ # ! ~ ` 'space', etc..)

function validateForOnlyEmail(txt) { txt.value = txt.value.replace(/[^A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}]+/g, ''); }

Thanks!

update

Ok, how would i just block those special characters above using RegEX?

StealthRT
  • 10,108
  • 40
  • 183
  • 342
  • I think most (if not all) of those characters you mentioned are valid in email addresses - http://en.wikipedia.org/wiki/E-mail_address#RFC_specification – Matt Wilko Aug 22 '12 at 14:34
  • Update - you **shouldn't** be blocking !#$%&'*+-/=?^_`{|}~ – Matt Wilko Aug 22 '12 at 14:47
  • @StealthRT Y dnt you block those characters at `keypress` itself...`blocking` and `replacing` those special characters above using `RegEX` doesn't make **sense** – Anirudha Aug 22 '12 at 15:03

1 Answers1

2

If you want to validate an Email Address Regex is not the right choice..

Use MailAddress as recommended by our own geek SLaks

try 
{
   address = new MailAddress(address).Address;
} 
catch(FormatException) 
{
   //address is invalid
}
Community
  • 1
  • 1
Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • 1
    +1 Agree regex is not the solution: Here is some sample regex to validate an email address http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html – Matt Wilko Aug 22 '12 at 14:43
  • 1
    I have to disagree about this as a solution for a couple of reasons. First, this is a server side solution whereas the request was for a JavaScript solution. Secondly, from a lot of experience using the MailAddress object it is quite poor at allowing through it invalid email addresses as well as rejecting valid email addresses. If you are using System.Net.Mail to send the emails then it is a moot point but this is not a fool proof way of validating email addresses. – rrrr-o Aug 22 '12 at 14:47
  • @rrr `Regex` is also not a fool proof way to do! – Anirudha Aug 22 '12 at 15:11