0

Possible Duplicate:
Validate email address in Javascript?

I have to do validation for Email format, I am using the CODE below line to restrict Special Characters.

onkeypress="return AlphaNumericBox(event,this,'@._);"

But now the Problem is I don have any proper validation for the exact format for example its also accepting text like " @abcd.com.gmail,.. " Is there any javascript validation for this? any idea?

Thanks in advance.

Community
  • 1
  • 1
Lakshmitha
  • 675
  • 3
  • 11
  • 17
  • see [this][1] [1]: http://stackoverflow.com/questions/46155/validate-email-address-in-javascript – sym3tri Nov 22 '11 at 05:53
  • 2
    There is a far greater chance that a user will enter an invalid or incorrect e–mail address that passes the rules for an e–mail address format than enter an invalid format. The best (i.e. only reliable) solution to checking that a user has entered their e–mail address correctly is to send an e–mail to that address and see if they respond. – RobG Nov 22 '11 at 06:03
  • @sym3tri: For urls in comments use next markup: `[ text ] ( url )` (w/out spaces of course), e.g. [this](http://stackoverflow.com/questions/46155/validate-email-address-in-javascript) – abatishchev Nov 22 '11 at 07:44
  • the response are here :https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript/1373724#1373724 – Saliou673 Aug 27 '18 at 03:17

2 Answers2

2
function CheckEmail(address){
    address=address.replace(/(^\s*)|(\s*$)/g, "");
    var reg=/([\w._-])+@([\w_-])+(\.([\w_-])+){1,2}/;
    var matcharr=reg.exec(address);
    if(matcharr!=null){
        if(matcharr[0].length==address.length){
            return true;
        }
        return false;
    }
    return false;
}

eg:
var sVal=" t.st@gmail.com.cn ";
var sVal2=" t.st@gmail.com.cn.abc ";
console.log(CheckEmail("name@server.com"));    //outpus true
console.log(CheckEmail("@server.com"));   //outpus false
artwl
  • 3,502
  • 6
  • 38
  • 53
1

I recommend that you use this function. I've tested it many times.

function validateEmail (emailAddress) {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
}

Now, you can easily validate any email address:

var isValid = validateEmail('name@server.com'); // returns true;
isValid = validateEmail('@server.com'); // returns false;
Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188