任何人都可以帮助找出我的代码出错的地方,即使表单字段无效,也无法阻止表单提交,我整天都在这里,并尝试了很多方法,但没有运气。
[Display(Name = "Amount to convert")]
[Required(ErrorMessage = " is required")]
[RegularExpression("^[0-9]+$", ErrorMessage = " requires numbers only")]
[Range(1, int.MaxValue, ErrorMessage = " must be more than 1")]
$(function() {
// $("#frmWeightsMeasures").validate();
$("#frmWeightsMeasures").submit(function(event) {
// var isvalidate = $("#frmWeightsMeasures").valid();
// if (isvalidate) {
event.preventDefault();
// }
$.ajax({
type: "POST",
cache: true,
url: form.attr("action"),
data: form.serialize(),
dataType: "json",
error: searchFailed,
success: function(weightsData) {
$("#DisplayConversion").html(weightsData.DisplayConversion);
}
});
});
});
function searchFailed(xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
$("#DisplayConversion").html("Sorry, there was a problem with the search.");
}
我已经添加了下面的工作代码,希望它可以帮助未来的某个人,故事的主题,修改你的代码,看你删除的内容。
$(function() {
$("#frmWeightsMeasures").validate();
$("#frmWeightsMeasures").submit(function(event) {
var isvalidate = $("#frmWeightsMeasures").valid();
if (isvalidate) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
cache: true,
url: form.attr("action"),
data: form.serialize(),
dataType: "json",
error: searchFailed,
success: function(weightsData) {
$("#DisplayConversion").html(weightsData.DisplayConversion);
}
});
}
});
});
function searchFailed(xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
$("#DisplayConversion").html("Sorry, there was a problem with the search.");
}
答案 0 :(得分:2)
你实际上并没有引用表单,这就是为什么它说它未定义。你需要在你的ajax调用之前加上以下内容:
var form = $(this);
另外,对于验证:
return $(form).valid()
会阻止表单提交无效
答案 1 :(得分:1)
您可能想尝试event.preventdefault()和event.stopPropagation()
单独使用preventdefault仍然会让错误冒出来,这可能不是你想要的。
答案 2 :(得分:0)
我认为最好的是在出错时返回false,而不是.preventDefault();