Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mark a field as required 'on the fly'

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.

like image 533
SamWM Avatar asked Nov 13 '22 13:11

SamWM


1 Answers

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  }); }
like image 137
amelvin Avatar answered Nov 27 '22 16:11

amelvin