Search code examples
javascriptasp.netregexemail-validation

Using REGEX for email


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?


Solution

  • 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
    }