1

I have 5 or so fields that will be hidden or shown based on the value of a drop down list; however, if they are visible, I need them to be required.

Is there a way to dynamically turn on/off unobtrusive validation for these fields?

Here is some code:

<div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-md-4 control-label">Routing Number</label>
                    <div class="col-md-8">
                        <input id="RoutingNumber" asp-for="org.RoutingNumber" class="form-control " autocomplete="off" />
                        <span asp-validation-for="org.RoutingNumber" class="text-danger"></span>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-md-3 control-label">Account Holder Name</label>
                    <div class="col-md-9">
                        <input id="AccountHolderName" asp-for="org.AccountHolderName" class="form-control " autocomplete="off" />
                        <span asp-validation-for="org.AccountHolderName" class="text-danger"></span>
                    </div>
                </div>
            </div>
        </div>

I would need these fields to be required, ONLY IF a separate drop down list had a certain value

websculpt
  • 53
  • 9
  • Probably yes, but it's hard to answer without seeing the way you are doing validation. There are a lot of approaches. Can you post some code? – John Wu Jan 15 '18 at 17:13
  • Thank you for your comments, I just added some code -- keep in mind this is MVC, and I need to continue to use the unobtrusive validation, as it is how I am validating everything on the site – websculpt Jan 15 '18 at 17:27
  • Use conditional validation attributes. For example a [foolproof](http://foolproof.codeplex.com/) `[RequiredIf]` attribute, or to write your own, refer [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](https://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) –  Jan 15 '18 at 19:57
  • @VtoCorleone, That link is for HTML-5 validation, not MVC's unobtrusive client side validation (HTML-5 validation is not applicable when using unobtrusive validation) –  Jan 15 '18 at 20:01
  • For now, I am placing this in the form: onsubmit="return PreValidation(Event)" and adding custom attributes to my elements, marking them as required, and checking them, and returning "true" -- which continues with the submission of the form – websculpt Jan 16 '18 at 05:03
  • Thanks for the clarification @StephenMuecke. I removed my comment. – VtoCorleone Jan 16 '18 at 05:26
  • Possible duplicate of [How to set HTML5 required attribute in Javascript?](https://stackoverflow.com/questions/18770369/how-to-set-html5-required-attribute-in-javascript) – wscourge Jan 16 '18 at 05:43

0 Answers0