C0ol_Cod3r C0ol_Cod3r - 5 months ago 19
jQuery Question

JQuery Validation Plugin not working with Email type right?

I have configured a Grunt file to build a single JS file with all my libraries and my code, so I only have the single JS file to included in my site. This is all working fine but I have just added the JQuery Validate plugin into it (http://jqueryvalidation.org/) and this plugin is working but not completely, I take it for red that its my code and how I have built it.

But I have a number of forms, and once of which is changing the users email. I should also say here that I am building the this site using CakePHP with its form helpers (although that side of the site is fully working without any errors).

This is the code I am using:

$( "#EmailChange" ).validate({
rules: {
'data[Email][currentemail]':{
required: true,
email: true
},
'data[Email][newemail]':{
required: true,
email: true
},
'data[Email][emailconfirm]': {
equalTo: "#NewEmail", <-id for the [email][newemail] input
required: true,
email: true
}
},
messages: {
'data[EmailUpdate][currentemail]': "email address is needed",
'data[EmailUpdate][newemail]': "a vaild email address is needed",
'data[EmailUpdate][emailconfirm]': "second email does not match",
}
});


Now this works, sort of but does not verify my email address right, I will enter,
someemail@something
and this would remove or come back as valid email, before the domain suffix is entered. When I use the test field on the email on there own website, it does not do this, it only comes back as valid after the user inputs the suffix.

So what am I doing wrong?

Thanks.

Answer

Use following code for email :

jQuery.validator.addMethod("validEmail", function(value, element) 
{
    if(value == '') 
        return true;
    var temp1;
    temp1 = true;
    var ind = value.indexOf('@');
    var str2=value.substr(ind+1);
    var str3=str2.substr(0,str2.indexOf('.'));
    if(str3.lastIndexOf('-')==(str3.length-1)||(str3.indexOf('-')!=str3.lastIndexOf('-')))
        return false;
    var str1=value.substr(0,ind);
    if((str1.lastIndexOf('_')==(str1.length-1))||(str1.lastIndexOf('.')==(str1.length-1))||(str1.lastIndexOf('-')==(str1.length-1)))
        return false;
    str = /(^[a-zA-Z0-9]+[\._-]{0,1})+([a-zA-Z0-9]+[_]{0,1})*@([a-zA-Z0-9]+[-]{0,1})+(\.[a-zA-Z0-9]+)*(\.[a-zA-Z]{2,3})$/;
    temp1 = str.test(value);
    return temp1;
}, "Please enter valid email.");

In rules use following

rules: {

    'data[Email][newemail]': {
        required: true,
        validEmail: true
    }
}
Comments