Bappa Bappa - 2 months ago 17
Javascript Question

TLD validation for email address in javascript

I am validating an email address. But this is not validating whether I am using proper tld or not. I want to validate only for .com,.in,.org,.gov and .jo .How to do that? My code is like:

function validateConsumerEmail(){
email = document.getElementById('customer_email').value;
if ((email == null)||(email == "")){
alert("Please Enter a Valid Consumer Email Address...")
document.consumerEmail.customer_email.focus();
return false
}
if (echeck(email)==false){
email=""
document.consumerEmail.customer_email.focus();
return false
}
if(email != ''){
var splitting = email.split('@');
if(!isNaN(splitting[0])){
alert('Please provide proper email address...');
document.consumerEmail.customer_email.focus();
return false;
}
if(splitting[0].length<6 || splitting[0].length > 250){
alert('Please provide proper email address...');
document.consumerEmail.customer_email.focus();
return false;
}

}
}


where customer_email is the id of the field name.

function echeck(str) {

var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert("Please provide valid email ID.");
return false
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Please provide valid email ID.");
return false
}

if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Please provide valid email ID.");
return false
}

if (str.indexOf(at,(lat+1))!=-1){
alert("Please provide valid email ID.");
return false
}

if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert("Please provide valid email ID.");
return false
}

if (str.indexOf(dot,(lat+2))==-1){
alert("Please provide valid email ID.");
return false
}

if (str.indexOf(" ")!=-1){
alert("Please provide valid email ID.");
return false
}

return true
}

Answer

Try this. For validation of e-mail addresses you really want to use REGEX, because your current code allows through all kinds of invalid e-mails, and doesn't allow many that are valid.

That said, being able to validate truly any valid e-mail is something of a discussion point and has been for years. My example is based on an adapted version of this e-mail-matcher REGEX.

I also simplified your code somewhat. I left out the call to echeck as you didn't provide this. Add it back in as required.

function validateConsumerEmail(){

    //prep
    var email = document.getElementById('customer_email'), error;

    //validate
    if (!email.value || !/^[\w\.%\+\-]+@[a-z0-9.-]+\.(com|gov|in|jo|org)$/i.test(email.value))
        error = 'Please enter a valid e-mail, with the domain .com, .in, .org, .jo or .gov';

    //feedback
    if (error) {
        email.focus();
        return false;
    } else {
        //OK - do something here
    }

}

‚Äč