我正在尝试使用jQuery验证忽略整个表单上所需的验证但似乎无法使其正常工作,这是在使用@html帮助程序的MVC项目上,因此我无法为元素添加名称为了验证,我也无法删除验证,然后使用jQuery将其全部添加回来,因为不是所有字段都是必需的,我将把我当前的java放在下面,任何帮助将不胜感激
$("body").on("click", ".next", function(e) {
e.preventDefault();
var btn = $(this);
var form = btn.closest("form");
form.validate({
rules: {
required: false
}
});
//check if form is valid
if (form.valid()) {
var out = form.validate({
rules: {
required: true
}
});
if (form.valid()) {
alert("valid and complete");
} else {
alert("valid but not complete");
}
} else {
showSysMessage("Invalid Data. Please Check the Data in the Highlighted Fields", {
color: "#FFB347"
});
};
});
修改
这个验证器需要验证超过300个字段的多个不同部分,因此使用每个单独元素的名称将是不切实际的,所以我想知道是否有办法验证表单而不验证输入所需的,希望这有帮助
编辑2
我的模型我有[必需]所需的字段,但是我想在验证上进行第一阶段检查输入的数据是否有效,如果是,它会将这些保存到数据库中允许页面更改,然后验证的第二步需要检查是否已填写模型中已设置为所需的所有元素,以及是否已返回表单已完成
以下是我的模型样本
[Required]
[Display(Name = "Title")]
public int? TitleID { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Middle Names")]
public string Middlename { get; set; }
[Required]
[Display(Name = "Surname")]
public string Surname { get; set; }
[Required]
[Display(Name = "Date of Birth")]
public DateTime? DateOfBirth { get; set; }
[Required]
[Display(Name = "Nationality")]
public string Nationality { get; set; }
[Required]
[Display(Name = "Martial Status")]
public int? StatusMaritalID { get; set; }
[Required]
[Display(Name = "NI Number")]
public string NINumber { get; set; }
[Required]
[Display(Name = "Have you been known by diffrent names?")]
public bool? IsKnownByOtherNames { get; set; }
[Required]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Required]
[Display(Name = "Mobile Number")]
public string MobileNumber { get; set; }
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
以下是获取任何已填写数据的控制器示例
model.TitleID = data.TitleID;
model.FirstName = data.FirstName;
model.Middlename = data.Middlename;
model.Surname = data.Surname;
model.DateOfBirth = data.DateOfBirth;
model.Nationality = data.Nationality;
model.StatusMaritalID = data.StatusMaritalID;
model.NINumber = data.NINumber;
model.IsKnownByOtherNames = data.IsKnownByOtherNames;
model.PhoneNumber = data.PhoneNumber;
model.MobileNumber = data.MobileNumber;
model.Email = data.Email;
以下是保存控制器的示例
data.TitleID = model.TitleID;
data.FirstName = model.FirstName;
data.Middlename = model.Middlename;
data.Surname = model.Surname;
data.DateOfBirth = model.DateOfBirth;
data.Nationality = model.Nationality;
data.StatusMaritalID = model.StatusMaritalID;
data.NINumber = model.NINumber;
data.IsKnownByOtherNames = model.IsKnownByOtherNames;
data.PhoneNumber = model.PhoneNumber;
data.MobileNumber = model.MobileNumber;
data.Email = model.Email;
以下是正在使用的视图
<h2>Personal Details</h2>
<div class="row-fluid">
<div class="span3">
@Html.LabelFor(x => x.TitleID)
@Html.DropDownListFor(x => x.TitleID, Model.Titles, "-- Please Select --", new { @class = "input-block-level" })
@Html.LabelFor(x => x.DateOfBirth)
@Html.TextBoxFor(x => x.DateOfBirth, "{0:dd/MM/yyyy}", new { @class = "input-block-level date-picker" })
</div>
<div class="span3">
@Html.LabelFor(x => x.FirstName)
@Html.TextBoxFor(x => x.FirstName, new { @class = "input-block-level" })
@Html.LabelFor(x => x.Nationality)
@Html.TextBoxFor(x => x.Nationality, new { @class = "input-block-level" })
</div>
<div class="span3">
@Html.LabelFor(x => x.Middlename)
@Html.TextBoxFor(x => x.Middlename, new { @class = "input-block-level" })
@Html.LabelFor(x => x.StatusMaritalID)
@Html.DropDownListFor(x => x.StatusMaritalID, Model.StatusMaritals, "-- Please Select --", new { @class = "input-block-level" })
</div>
<div class="span3">
@Html.LabelFor(x => x.Surname)
@Html.TextBoxFor(x => x.Surname, new { @class = "input-block-level" })
@Html.LabelFor(x => x.NINumber)
@Html.TextBoxFor(x => x.NINumber, new { @class = "input-block-level" })
</div>
</div>
<h3>Contact Details</h3>
<div class="row-fluid">
<div class="span3">
@Html.LabelFor(x => x.PhoneNumber)
@Html.TextBoxFor(x => x.PhoneNumber, new { @class = "input-block-level" })
</div>
<div class="span3">
@Html.LabelFor(x => x.MobileNumber)
@Html.TextBoxFor(x => x.MobileNumber, new { @class = "input-block-level" })
</div>
<div class="span6">
@Html.LabelFor(x => x.Email)
@Html.TextBoxFor(x => x.Email, new { @class = "input-block-level", type="email" })
</div>
</div>
<div class="row-fluid">
<div class="checkbox span12" style="padding-left:0;">
@Html.CheckBox("IsKnownByOtherNames", Model.IsKnownByOtherNames != null && (bool)Model.IsKnownByOtherNames)
@Html.LabelFor(x => x.IsKnownByOtherNames)
</div>
</div>
最后这是我的整个保存脚本
$("body").on("click", ".next", function(e){
debugger;
e.preventDefault();
var btn = $(this);
var form = btn.closest("form");
form.validate({
rules: {
required: false
}
});
//check if form is valid
if (form.valid()) {
var out = form.validate({
rules: {
required: true
}
});
if (form.valid()) {
// disable the button to prevent multiple posts
btn.prop("disabled", true);
// serialise the form fields into an array
var fields = form.serializeArray();
// create a blank object to stuff the parameters into for the ajax call
var params = {};
// loop over the array and create a property for each item in array
// in the format expected by the controller action
$.each(fields, function (index, element) {
params[element.name] = element.value;
});
//loop over all checkboxes and see if they are checked or not
var checkboxes = form.find("input:checkbox")
$.each(checkboxes, function (index, element) {
params[element.name] = $(element).is(":checked");
});
// Make the ajax post call
// passing the parameters
$.post("UpdateCheck", params)
.success(function (data) {
alert("valid and complete");
// if fail alert the user of fail with error
if (data == false) {
//Create a toast message alerting of fail with reason
showSysMessage("Failed to Save. (Data Error)", { color: "#FFB347" });
// re-enables button
btn.prop("disabled", false);
} else {
btn.prop("disabled", false);
var currentpage = parseInt($(".TinyDancer").attr("data-currentpage"))
var newpage = currentpage + 1;
$.post("Page"+PageNos[newpage], {id:@Model.ID }).success(function(html){
$("#WizardStage").val(PageNos[newpage]);
$(".page[data-pageno='" + PageNos[newpage] + "']").parent().addClass("active").siblings().removeClass("active");
$(".TinyDancer").slideUp(function(){$(".TinyDancer").html(html).promise().done(function() {$(".TinyDancer").slideDown();});});
$(".TinyDancer").attr("data-currentpage", newpage);
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
});
}
}).fail(function () {
showSysMessage("Failed to Save. (Network Transport Error))", { color: "#FFB347" });
});
} else {
alert("valid but not complete");}
}else{
showSysMessage("Invalid Data. Please Check the Data in the Highlighted Fields", { color: "#FFB347" });
};
});
答案 0 :(得分:2)
默认情况下,MVC将属性名称作为输入的名称,默认情况下需要在值类型中添加,我不知道您的视图模型,也许您有一个值类型字段不是&t; t在这种情况下需要使其成为可以解决的问题
答案 1 :(得分:0)
感谢Stephen Muecke指出我正确的方向,我终于提出了一个完全动态的解决方案,它应该适用于每个单独的字段,而不需要单独的页面/部分或模型。
要做到这一点首先,在您加载页面/部分运行此脚本时,将一个名为isRequired的类添加到所有必需元素
var fields = $("form").find("input[data-val]");
$.each(fields, function (index, element) {
$(element).addClass("isRequired")
});
接下来要做的就是像这样格式化验证脚本
$("body").on("click", ".next", function(e){
e.preventDefault();
var btn = $(this);
var form = btn.closest("form");
$.each($('.isRequired'), function (index, element) {
$(element).rules('add', {
required: false // set a new rule
});
});
form.validate();
//check if form is valid
if (form.valid()) {
$.each($('.isRequired'), function (index, element) {
$(element).rules('add', {
required: true // set a new rule
});
});
form.validate();
if (form.valid()) {
alert("Form is Completed and Valid")
} else {
alert("Form is Valid but not complete");}
}else{
alert("Data Enter in some of the fields is of an Invalid Type")
};
});