Reputation: 107
I want to make sure the visitor is entering a valid email address and a password. If yes, then fade in the submit button. Otherwise fade it out (keep it hidden).
How do I add functionality for making sure there is an @ character as well as a . character in the emailLen string?
var emailLen = $("#email").val().length
var pwordLen = $("#pword").val().length
if (emailLen > 7 && pwordLen > 5) {
$('#btnSubmit').animate({ opacity: 1.0 }, 200);
}
else {
$('#btnSubmit').animate({ opacity: 0.0 }, 200);
}
Thanks
Upvotes: 2
Views: 1385
Reputation: 46329
To answer your question directly, you can check if certain characters exist like this:
var email = $("email").val();
var emailLen = email.length;
// important bit:
var hasAt = email.indexOf( "@" ) != -1;
var hasDot = email.indexOf( "." ) != -1;
or you can go a step further and check that at least one . is after the last @
var atPos = email.lastIndexOf( "@" );
var hasAt = atPos != -1;
var hasDot = email.indexOf( ".", atPos ) != -1;
The answer given by OSSCube is the more usual way of checking email addresses, but you should beware of unusual emails (such as those using IP addresses, quotes, or escaped characters). I believe that this method (simply checking [anything]@[anything].[anything]
) will never have a false negative (shout up in the comments if I'm wrong!)
Upvotes: 1
Reputation: 15593
Use regular expersion to verify the email adddress:
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = $("#email").val();
var pwordLen = $("#pword").val().length;
if (regex.test(email) && pwordLen > 5) {
$('#btnSubmit').animate({ opacity: 1.0 }, 200);
}
else {
$('#btnSubmit').animate({ opacity: 0.0 }, 200);
}
regex.test(email)
will return true if it is valid email id else return false.
Upvotes: 2