jQuery validation - Textbox requires data if checkbox is checked -
i have checkbox - hasraffle
require textbox - raffleitem
contain data if hasraffle
checked. how this? i've never done own jquery validations before. attempted, it's not working @ all. 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 test!!" } } } });
edit: here's 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> }
you need add custom rule 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 rule :
rules: { 'raffleitem': { 'checkraffle' : true } }
this code not tested (and probly not work becuase cant see dom), if can see logic behind code can debug your!
Comments
Post a Comment