我有一个复选框 - HasRaffle
,如果选中RaffleItem
,则需要一个文本框 - HasRaffle
来包含数据。我该怎么做?我以前从未做过自己的jQuery验证。这就是我的尝试,但它根本不起作用。我甚至关闭了吗?
$("#donationEventForm").validate({
rules: {
RaffleItem: {
required: function () {
if ($("#HasRaffle").is(":checked")) {
if ($("#RaffleItem").val === '') {
return true;
} else {
return false;
}
} else {
return false;
}
},
messages: {
required: "This is a test!!"
}
}
}
});
编辑:这是我的观点
@using (Html.BeginForm("Create", "DonationEvent", FormMethod.Post, new {id = "donationEventForm"})) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(false)
<div class="form-field">
@Html.LabelFor(model => model.Charity)
@Html.TextBoxFor(model => model.Charity)
@Html.ValidationMessageFor(model => model.Charity)
</div>
<div class="form-field">
@Html.LabelFor(model => model.StartDate)
@Html.TextBoxFor(model => model.StartDate, new {@class = "datepicker"})
@Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="form-field">
@Html.LabelFor(model => model.EndDate)
@Html.TextBoxFor(m => m.EndDate, new {@class = "datepicker"})
@Html.ValidationMessageFor(model => model.EndDate)
</div>
<div class="form-field">
@Html.Label("Raffle?")
@Html.CheckBox("HasRaffle", true)
</div>
<div class="form-field">
@Html.LabelFor(model => model.RaffleItem)
@Html.TextBoxFor(model => model.RaffleItem)
@Html.ValidationMessageFor(model => model.RaffleItem)
</div>
@Html.TextBoxFor(model => model.GLCode, new {@type = "hidden"})
@Html.TextBoxFor(model => model.TransactionDescription, new {@type = "hidden"})
@Html.TextBoxFor(model => model.CreatedBy, new {@type = "hidden"})
<div class="form-field-buttons">
<input type="submit" value="Create" />
<input type="button" value="Cancel" onclick="location.href='../Home/Index'"/>
</div>
}
答案 0 :(得分:2)
您需要使用addMethod
添加自定义规则jQuery.validator.addMethod('checkRaffle', function(value, element){
if ($("#HasRaffle").is(":checked")) {
if (value === '') {
return false;
} else {
return true;
}
} else {
return true;
}
}, 'Please write something')
然后规则看起来像那样:
rules: {
'RaffleItem': {
'checkRaffle' : true
}
}
此代码未经过测试(由于我无法看到您的DOM,因此很可能无法正常工作),但如果您能看到我的代码背后的逻辑,您可以调试它!