2015-09-23 35 views
0

因此,我得到了一個表單提交的js代碼,並且一切正常,但是,我不知道在代碼中寫入的內容和內容,以便電子郵件得到驗證檢查。我應該寫什麼和在哪裏進行驗證檢查電子郵件?使用Javascript進行電子郵件驗證在AJAX之前

$(document).ready(function() { 
    $("#submit").click(function() { 

    var name = $("#fullname2").val(); 
    var email = $("#fullemail2").val(); 
    var state = $("#selectstate").val(); 
    // Returns successful data submission message when the entered information is stored in database. 
    var dataString = 'FullName=' + name + '&email=' + email + '&SovereignState=' + state; 
    if (name == '' || email == '' || state == '') { 
     $('#required_fields').show(); 
    } else { 
     // AJAX Code To Submit Form. 
     $.ajax({ 
     type: "POST", 
     url: "demo.php", 
     data: dataString, 
     cache: false, 
     success: function(phpSays) { 
      if (phpSays == "OK") { 
      $('#email_error').show(); 
      $('#required_fields').hide(); 
      } else { 
      $('#sinatra2').hide(); 
      $('#thanks').fadeIn(1000); 
      $('#spreading_message').delay(1800).fadeIn(1500); 
      $('#by_social').delay(3000).fadeIn(1500); 
      $('#email_error').hide(); 
      $('#required_fields').hide(); 
      } 
     } 
     }); 
    } 
    return false; 
    }); 
}); 
+0

可能重複的http://計算器。 com/questions/2855865/jquery-regex-validation-of-e-mail-address –

+1

可能重複的[在JavaScript中驗證電子郵件地址?](http://stackoverflow.com/questions/46155/validate-email-address- in-javascript) –

回答

1

尋找可以提出以下方法來說,你可以做電子郵件驗證

if(name==''||email==''||state=='') 
{ 
    $('#required_fields').show(); 
}//this is fine 
else if(!valid(email))//call a function which validates email and returns true or false 
{ 
    //Display the message either with same $('#required_fields') changing the text or 
    //Add one more field to display invalid email message 
} 
else 
{ 
    //Your ajax call here 
} 

現在您的有效功能將類似於

function valid(email) 
{ 
    var emailReg = /^([\w-\.][email protected]([\w-]+\.)+[\w-]{2,4})?$/; 
    return emailReg.test(email); //this will either return true or false based on validation 
} 
+0

謝謝,但你能解釋更多的功能離子?我是否需要編寫if語句(如果爲「真」)? – Chris

+1

沒關係,我只是意識到它完美的作品,謝謝! – Chris

+0

沒有..''emailReg.test'爲你做驗證..任何時候..快樂編碼.. :) –

1
$(document).ready(function(){ 
$("#submit").click(function(){ 

var name = $("#fullname2").val(); 
var email = $("#fullemail2").val(); 
var state = $("#selectstate").val(); 
// Returns successful data submission message when the entered information is stored in database. 
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state; 
if(name==''||email==''||state=='') 
{ 
$('#required_fields').show(); 
} 
else 
{ 
// AJAX Code To Submit Form. 
    // <-- email address should be here 
    ...........  
} 
return false; 
}); 
}); 
1

更好的地方來驗證就是你有 'fullemail2' 輸入字段。即使在JavaScript文件中,您也應該在創建dataString之前執行此操作。這樣你可以在提交之前進行驗證。你的代碼我

相關問題