Using ASP.NET MVC3, Razor and jQuery Unobtrusive validation (as provided out of the box by Microsoft).
How can you mark fields as required 'on the fly', i.e. only in certain circumstances? For example, if user is in the role 'publisher', there is a 'Publish Date' and 'Publish' button. The 'Publish Date' field is required when the 'Publish' button is pressed, but not when the 'Save Draft' button is. If the user is not in that role, then the 'Publish' button is not shown in the form and therefore not required.
I'm sure this is not something that can be done out of the box and extra code is required both client side (jQuery Validate) and server side. If it can, it is not obvious how it can be done.
If you were doing this in webform-land you would instantiate a RequiredFieldValidator in the button's click event handler and apply it to the field that should become required.
In mvc-land this isn't obvious. This SO question/answer demonstrates how to handle a button click - you may be able to extend it to instantiate a RequiredFieldValidator and apply it to the field.
In jquery you can add something like:
$("#buttonid").on("click", function() { $("#fieldToBeRequiredId").rules("add", {
required: true }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With