Reputation: 2005
I have a checkbox - HasRaffle
that will require a textbox - RaffleItem
to contain data if HasRaffle
is checked. How would I do this? I've never done my own jQuery validations before. This is what I attempted, but it's not working at all. Am I even close?
$("#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!!"
}
}
}
});
EDIT: Here's my View
@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>
}
Upvotes: 0
Views: 2931
Reputation: 33880
You need to add a custom rule with 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')
Then the rule would look something like that :
rules: {
'RaffleItem': {
'checkRaffle' : true
}
}
This code is not tested (and will probly not work becuase i cant see your DOM), BUT if you can see the logic behind my code you can probably debug your!
Upvotes: 2