Reputation: 99
I need to make my email and telephone validated for the contact form.. theres code in there for email but its incorrect and not the proper way any help! i know it needs to were it says:
if(email.length == 0 || email.indexOf('@') == '-1')
but im now sure how to do this im very new to php, so go easy on me :)
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
var tel = $('#tel').val();
// Form field validation
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(tel.length == 0){
var error = true;
$('#tel_error').fadeIn(500);
}else{
$('#tel_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('@') == '-1'){ **this is not the right way! help**
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
}else{
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
if(tel.length == 0){
var error = true;
$('#tel_error').fadeIn(500);
}else{
$('#tel_error').fadeOut(500);
}
Upvotes: 0
Views: 120
Reputation: 343
email regex: http://www.regexlib.com/Search.aspx?k=email
telephone regex: http://www.regexlib.com/Search.aspx?k=telephone
using regex and jquery to validate fields: https://stackoverflow.com/a/709358/2646455
so you could do something like this:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
$('#email').rules("add", { regex: "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$" });
You could follow suit with the other fields, either applying regex (like, for the telephone) or other, basic, jquery validations.
p.s. You only need to call $.validator.addMethod
once, to make the regex validation option available. Then you call the last line once for each validation rule you want to apply to each field (you can apply more than one validation rule to a single field).
Upvotes: 1
Reputation:
var atposition = email.indexOf("@"); //email = $('#email').val();
var dotposition = email.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=email.length)
{
//Invalid Email Code
}
Upvotes: 0