2014-04-16 57 views
-2

我试图发送一个表格到电子邮件,但我想名称字段进行验证(如果没有内容,则不发送) 我无法验证,然后通过PHP脚本结束我有正确的工作 I have created a jsfiddle at the following link 有人可以帮忙吗?发送之前需要验证表格

$(document).ready(function() { 
$('.form-horizontal').on('submit', function (e) { 

    e.preventDefault(); 
    var name = $('#name').val(); 
    if (!name) { 
     showError(); 
    } 
    else { 
     $('#contact-form').submit(); 
    } 

}); 

function showError() { 

    $('.tyler-error').show(); 
} 

}); 
+1

“我无法得到它的工作。”继续... – Bucket

+2

永远不要依赖于客户端验证。无论您是否能够正常工作,您仍然需要在服务器上进行验证。 –

+4

你忘了在小提琴中选择jquery库。 http://jsfiddle.net/4TuVU/4/ – karthikr

回答

3

Working fiddle

在你的小提琴,你没有从库下拉列表中选择jQuery的。其次,您应该避免在提交处理程序中提交表单,而应该在preventDefault(如果存在验证错误)时提交表单。

$('.form-horizontal').on('submit', function (e) { 
    var name = $('#name').val(); 
    if (!name) { 
     showError(); 
     e.preventDefault(); 
    } 
}); 

如果你真的想保持代码,因为它是,你需要调用的形式提交功能,而不是jQuery的提交功能:

$('#contact-form')[0].submit(); 
// or 
$('#contact-form').get(0).submit(); 

这里,[0].get(0)是给你的普通的JavaScript DOM元素,不包含jQuery包装,因此您可以拨打submit()

1

HTML5提供输入验证,您可以设置为了告诉浏览器您的html视图是HTML5。

//Set your doctype for HTML5. 
<!doctype html> 
<html> 
<head> 
    <title></title> 
</head> 
<body> 
    <form id="the_form"> 
     //here html5 will not submit if the box is empty or does not meet the email 
     //addres format. 
     <input type="email" name="email" id="email" placeholder="Enter email.."> 
     <input type="submit" value="send"> 
    </form> 
</body> 
</html> 

如果你不想使用HTML5,你也可以做,如果输入的是空一个简单的JavaScript代码无法提交。

<html> 
<head> 
    <title></title> 
    <script type="text/javascript"> 
    window.onload = init(); 

    function init(){ 
     //get form. 
     var form = document.getElementById("the_form"); 

     form.onsubmit = email_validation; 
    } 

    function email_validation(){ 
     email = document.getElementById("email"); 

     if(email.value == ''){ 
      //return false to avoid submission. 

      return false; 
     } 
     else{ 
      //do whatever code. 
     } 
    } 
    </script> 
</head> 
<body> 
    <form id="the_form"> 
     <input type="text" name="email" id="email" placeholder="Enter email.."> 
     <input type="submit" value="send"> 
    </form> 
</body> 
</html> 

用这种方式,您的电子邮件将在发送之前进行验证,希望为您工作。