【发布时间】:2014-05-15 14:29:08
【问题描述】:
当三个字段包含除数字以外的任何字符时,我正在尝试使用 jQuery Validate 来阻止我的 ajax 表单提交。显然我做错了什么,但我看不到什么。
编辑:似乎有两个错误。我的验证规则使用字段 ID 而不是字段名称。但是,在解决了这个问题后,表单仍然会意外验证..
这是我的 jQuery 代码:
(function() {
$(document).ready(function() {
formSubmits();
/**
* Handles all the form submits that go on.
* This is primarily the ID search and the form submit.
*/
function formSubmits() {
/*** SAVE RECIPE ***/
// validate form
$("#category-editor").validate({
rules: {
"time-prep": {number: true}, /* not sure why validation doesn't work.. */
"time-total": {number: true}, /* according to this, it should: http://goo.gl/9z2odC */
"quantity-servings": {number: true}
},
submitHandler: function(form) {
// submit changes
$.getJSON("setRecipe.php", $(form).serialize() )
.done(function(data) {
// de-empahaize submit button
$('.footer input[type=submit]')
.removeClass('btn-primary')
.addClass('btn-default');
});
// prevent http submit
return false;
}
});
}
});
})(jQuery);
这是我在 submitHandler 中放置断点时在检查器中看到的内容。尽管输入错误(值是 'dsdfd' 而不是 '123'),它仍会到达 submitHandler
这是相关的标记:
<form id="category-editor" class="form-inline" method="get">
....
<div class='form-group'>
<div>
<label for="time-prep">Prep time (min):</label>
<input value="" id="time-prep" name="activeTime" class="form-control min-calc jqValidateNum" data-calc-dest="time-prep-desc" type="number">
<input value="" id="time-prep-desc" name="activeTimeDesc" class="form-control subtle" type="text">
</div>
</div>
<div class='form-group'>
<div>
<label for="time-total">Total time (min):</label>
<input value="" id="time-total" name="totalTime" class="form-control min-calc jqValidateNum" data-calc-dest="time-total-desc" type="number">
<input value="" id="time-total-desc" name="totalTimeDesc" class="form-control subtle" type="text">
</div>
</div>
<div class='form-group'>
<div>
<label for="quantity-servings">Servings:</label>
<input value="" id="quantity-servings" name="servings" class="form-control jqValidateNum" type="number">
</div>
</div>
....
</form>
【问题讨论】:
-
您为什么要使用以下答案中的代码编辑您的 OP?现在 Pointy 的正确答案毫无意义,您问题中的代码应该可以正常工作。
-
表单的其余标记在哪里?
form标签在哪里? -
简单的火花。在你投反对票之前,在 cmets/edits 之间给我一点时间 - 这仍然是一个相关的问题。
-
Easy there doublejack...请告诉我哪里说我对你投了反对票?
-
您不应该以这样的方式编辑问题,以使完美的答案无效……这会让未来的读者感到困惑。 Pointy 修复了代码中最明显的损坏部分,因此您的问题应该继续反映这一点。
标签: javascript jquery ajax jquery-validate