在AJAX之前使用Javascript进行电子邮件验证

时间:2015-09-23 04:04:32

标签: javascript jquery ajax forms validation

所以我得到了一个表单提交的js代码,一切都运行正常,但是,我不知道在代码中写入的位置和内容,以便电子邮件获得验证检查。我应该写什么以及在哪里写验证检查电子邮件?

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

3 个答案:

答案 0 :(得分: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 :(得分:1)

更好的验证位置是'fullemail2'输入字段。即使在javascript文件中,也应该在创建dataString之前执行此操作。这样你就可以在提交之前进行验证。

答案 2 :(得分:1)

查看您的代码,我可以建议以下方法说明您可以在哪里进行电子邮件验证

<book>
    <idno type="online">3456789012345</idno>
    <idno type="subject">Environment</idno>
    <idno type="subject">Water</idno>
    <idno type="subject">Policy</idno>
    <idno type="code">E135</idno>
    <idno type="ID">43396</idno>
</book>

现在你的有效功能看起来像

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
}