冲突的Javascript阻止表单验证

时间:2011-08-07 22:41:59

标签: javascript jquery

我试图在表单提交到数据库之前验证它,但是它似乎与它相冲突并且它只是在没有任何值的情况下发送

继承我的表格:

<form method="post" action="send.php" id="theform" name="theform">
<input type="text" name="firstname" id="firstname" value="First Name" onFocus="this.value=''" class="yourinfo" ><br/>
<input type="text" name="lastname" id="lastname" value="Last Name" onFocus="this.value=''" class="yourinfo"><br/>
<input type="text" name="email" id="email" value="Email Address" onFocus="this.value=''" class="yourinfo"><br/>
<span style="color:#FFF; font-family:Arial, Helvetica, sans-serif; font-size:12px;">Ally McCoist will be sacked on</span>
<div id="datepicker"></div>
<input type="hidden" name="date" id="date">
<input type="image" src="images/submit-button-small.png" name="submit" id="submit" value="submit" style="margin-top:10px; margin-left:-2px;" >
</form>

继承我的验证javascript:

$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";

$("#theform").submit(function(e){                

    //Validate required fields
    for (i=0;i<required.length;i++) {
        var input = $('#'+required[i]);
        if ((input.val() == "") || (input.val() == emptyerror)) {
            input.addClass("needsfilled");
            input.val(emptyerror);
            errornotice.fadeIn(750);
        } else {
            input.removeClass("needsfilled");
        }
    }
    // Validate the e-mail.
    if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
        email.addClass("needsfilled");
        email.val(emailerror);
    }

    //if any inputs on the page have the class 'needsfilled' the form will not submit
    if ($(":input").hasClass("needsfilled")) {
         e.preventDefault();
    } else {
         errornotice.hide();
    }


});

// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){       
   if ($(this).hasClass("needsfilled") ) {
        $(this).val("");
        $(this).removeClass("needsfilled");
   }
});
}); 

我的jquery UI datepicker页面上也有这个javascript,我认为可能会导致问题

<script>
        $(function() {
$("#datepicker").datepicker({
    altField: '#date'
});

$('#submit').click(function() {
    $('#output').html($('form').serialize());
});

});     

手指越过你们其中一个可以看到可以解决这个问题的东西

1 个答案:

答案 0 :(得分:0)

表单可能是由禁用JavaScript的人填写的,或者某个人或机器只是调用了HTTP POST,并且他们认为适合的值。出于这个原因,有必要在服务器端(即send.php)执行验证,而不仅仅是在客户端(在JavaScript文件中)。 JavaScript验证实际上只是一种UI优化,它允许用户在不需要与服务器进行往返通信的情况下立即被告知出现问题。从用户界面的角度来看,JavaScript验证很重要,但从安全角度来看,它是无用的。