2012-07-04 36 views
-1

我有一個JS函數的形式,用於檢查空字段和提交表單而不刷新所有頁面,我正在尋找一種方法來將電子郵件檢查功能整合到我現在擁有的功能中:Java腳本/ AJAX電子郵件檢查功能集成

$(function() { 
    $('.error').hide(); 
    $('input.text-input').css({backgroundColor:"#EBEBEB"}); 
    $('input.text-input').focus(function(){ 
    $(this).css({backgroundColor:"#EBEBEB"}); 
    }); 
    $('input.text-input').blur(function(){ 
    $(this).css({backgroundColor:"#EBEBEB"}); 
    }); 

    $(".button").click(function() { 
     // validate and process form 
     // first hide any error messages 
    $('.error').hide(); 
     } 

     var name = $("input#name").val(); 
     if (name == "") { 
     $("label#name_error").show(); 
     $("input#name").focus(); 
     return false; 
    } 
     var email = $("input#email").val(); 
     if (email == "") { 
     $("label#email_error").show(); 
     $("input#email").focus(); 
     return false; 
    } 
     var phone = $("textarea#phone").val(); 
     if (phone == "") { 
     $("label#phone_error").show(); 
     $("textarea#phone").focus(); 
     return false; 
    } 

     var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone; 
     //alert (dataString);return false; 

     $.ajax({ 
     type: "POST", 
     url: "process.php", 
     data: dataString, 
     success: function() { 
     $('#contact_form').html("<div id='message'></div>"); 
     $('#message').html("<h2>Email sent</h2>") 
     .hide() 
     .fadeIn(1000, function() { 
      $('#message').append("<img id='checkmark' src='images/check.png' />"); 
     }); 
     } 
    }); 
    return false; 
    }); 
}); 
runOnLoad(function(){ 
    $("input#name").select().focus(); 
}); 

感謝您的幫助。

+0

什麼是 「電子郵件檢查功能」你指的是?您的請求尚不清楚 – freefaller

回答

2

要檢查郵件,你可以使用:

var emailReg = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i 

function isEmail(email) { 
    return emailReg.test(email); 
} 
//call isEmail wherever you need it 

如果我可以在你的代碼進一步評論,我會建議您緩存您的選擇並重新使用它們:

var input = $('input.text-input'); 
input.css({backgroundColor:"#EBEBEB"}).focus(function() //... and so on 

而且,如果你的DOM的結構是正確的,你不必用輸入選擇器調用你的ID,它只是減慢你的實現,因爲它反覆遍歷DOM中的每個輸入,而不是直接獲取它。這意味着:

$("label#phone_error") // don't do this 
$("#phone_error") // do this 

此外,您還可以使用數據對象傳遞給jQuery的,所以不是

var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone; 

這樣做:

$.ajax(yoururl, {data: 
    { 
    name: name, 
    email: email, 
    phone: phone 
    }, // and so on