简体   繁体   中英

Want to validate my email and telephone

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);
}

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.

ps 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).

var atposition = email.indexOf("@");    //email = $('#email').val();

var dotposition = email.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=email.length)
  {
  //Invalid Email Code      
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM