mistery_girl mistery_girl - 6 months ago 20
jQuery Question

Email validation to display message only if email is entered but it is not a valid email

I want to display message that email address is not valid only if it is entered email address but it is not valid. If no value is entered, I don't want to display message - I just make input border red.

I tried this but it shows message even when field is empty:



function validateEmail($email) {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test( $email );
}
if($(element).hasClass('email')) {
if( !validateEmail($('.email'))) {
$('<span>Please enter a valid email address</span>').insertAfter($(element));
}
}





I also tried with qjeury validate plugin but in this case it doesn't show error for email at all:



var emails = ['email'];
for(var i=0;i< emails.length;i++) {
var email = emails[i];
rules[email] = {};
rules[email].email = true;
rules[email].required = true;
msgs[email] = {
required:'',
email : "Please enter a valid email address",
}
}

var validateObj = {}
validateObj["rules"] = rules;
validateObj["messages"] = msgs;
validateObj["onkeyup"] = function(element) { $(element).valid();};
validateObj["success"] = function(element) {};
validateObj["submitHandler"] = function (form) {
form.submit();
}
$("#form").validate(validateObj);




Answer

I really feel like I'm helping someone who didn't try to do it by himself...

You can use ($(element).val()) to test if your input is empty.

For this one to work, simply declare a empty-email class to color borders

if($(element).hasClass('email')) {
    if($(element).val()){
        if(!validateEmail($(element))) {
            $('<span>').text('Please enter a valid email address').insertAfter($(element));
        }
    }else{
        $(element).addClass('empty-email');
    }
}