我目前正在我的表单上使用 Jquery 验证。但是我也在使用ajax提交。当我单击提交时,尽管我进行了验证,但没有填写输入,表单仍会通过。请指教。
这是我的代码:
jQuery验证代码:
$(function() {
$("#mytestform" ).validate({
rules: {
aname: {
required: true,
minlength: 4,
maxlength: 20
},
req: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
},
},
messages: {
email: "Enter a valid email address.",
},
});
});
</script>
Here is my ajax code:
<script language="Javascript">
//var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$("#mytestform").submit(function(event) {
// Assign handlers immediately after making the request,// and remember the jqxhr object for this request
event.preventDefault();
var jqxhr = $.post("testme.php", $("#mytestform").serialize());
jqxhr.done(function(data, textStatus, jqXHR) {
//alert(textStatus + " second success " + data);
$('<p>Contact Form Submitted!</p>').prependTo('#mytestform');
}
);
jqxhr.fail(function(jqXHR, textStatus, errorThrown) { alert("There was an issue with your form" + " " + errorThrown); });
});
这是我的html:
<div id = "dvdform"> <!-- begin of form -->
<form id="mytestform" name="mytestform" action="testme.php" method="post">
<fieldset>
<legend><strong>Contact Me</strong></legend>
<div id= "formsection">
<div><p> <label for="aname">Name: </label> <input name="aname" class="boxform" minlength=4 />
</p> </div>
<div><p><label for="email">E-mail</label> <input type="text" name="email" maxlength="40"class="boxform" />
</p></div>
<div><p><label for="city">City</label> <input type="text" name="city" class="boxform" maxlength="40" />
<br />
</p></div>
<div><p><label for="country">Company</label> <input type="text" name="country" class="boxform" maxlength="40" />
<br />
</p></div>
<p><label for="country">Comments</label> <textarea name="req" class="required" cols="35" rows="30" style="height:100px;"> </textarea><br />
<br />
</p>
<div align="center" class="submitbox">
<input type="submit" value="SUBMIT" style="width:175px; height:20px;">
</div>
</div>
<!-- End of Form Section -->
</fieldset>
</form>
</div>
COMBINING IT using the submithandler still does not work:
$(function() {
$("#mytestform" ).validate({
rules: {
aname: {
required: true,
minlength: 4,
maxlength: 20
},
req: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
},
},
messages: {
email: "Enter a valid email address.",
},
submitHandler: function(form) {
var jqxhr = $.post("testme.php", $("#mytestform").serialize());
jqxhr.done(function(data, textStatus, jqXHR) {
//alert(textStatus + " second success " + data);
$('<p>Contact Form Submitted!</p>').prependTo('#mytestform');
}
);
jqxhr.fail(function(jqXHR, textStatus, errorThrown) { alert("There was an issue with your form" + " " + errorThrown); });
});
});
});
</script>