2

I am trying conditional required field. If user selects ContactByPhone checkbox I am showing ContactPhoneNumber field and it should be required filed. If user doesn't select ContactByPhone then ContactPhoneNumber is invisible and not required.

Validation is not showing on client side. and after I submit the form ModelState.IsValid is false for this property.

How to handle this? I think I referenced all scripts on the page. Do we have any alternative solution for this situation?

Model

public class Contact
{
  [Display(Name = "by Phone")]
  public bool ContactByPhone { get; set; }

  [RequiredIfTrue("ContactByPhone", ErrorMessage = "Phone number is required")]
  public string ContactPhoneNumber { get; set; }

}

Index.cshtml

<script src="~/Scripts/jquery.validate.min.js"></script>
   <script src="~/Scripts/jquery.mask.min.js"></script>
   <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
   <script src="~/Scripts/Index.js"></script>
   <script src="~/Scripts/jquery.notifyBar.js"></script>
   <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
   <script src="~/Scripts/mvcfoolproof.unobtrusive.min.js"></script>
   <div class="form-group">
        <div class="col-sm-5 text-left">
           @Html.Label("How do you want to be contacted?", new { @class = "control-label" })
        </div>
        <div class="col-sm-1">
          @Html.CheckBoxFor(model => model.ContactByPhone, new { @style = "margin-top: 8px"})
        </div>
    </div>
    <div class="form-group" id="divContactPhone" hidden>
        <div class="col-sm-5">
           @Html.LabelFor(model => model.ContactPhoneNumber, new { @class = "control-label-nobold" })<span class="red">*</span>
         </div>
         <div class="col-sm-4">
            @Html.TextBoxFor(m => m.ContactPhoneNumber, new { @class = "form-control" }) 
            @Html.ValidationMessageFor(m => m.ContactPhoneNumber, "", new { @style = "color:Red" })
          </div>
    </div>

Controller

enter image description here

Generated HTML

<div class="col-sm-4">
     <input class="form-control valid" data-val="true" data-val-requiredif="Phone number is required" data-val-requiredif-dependentproperty="ContactByPhone" data-val-requiredif-dependentvalue="True" data-val-requiredif-operator="EqualTo" id="ContactPhoneNumber" name="ContactPhoneNumber" type="text" value="" maxlength="15" autocomplete="off"> 
     <span class="field-validation-valid" data-valmsg-for="ContactPhoneNumber" data-valmsg-replace="true" style="color:Red"></span>
</div>
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
James123
  • 11,184
  • 66
  • 189
  • 343

1 Answers1

2

I guess you're missing MvcFoolproofJQueryValidation.min.js and MvcFoolproofValidation.min.js JS files. See example below:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true)

        <div class="form-group">
            <div class="col-sm-5 text-left">
                @Html.Label("How do you want to be contacted?", new { @class = "control-label" })
            </div>
            <div class="col-sm-1">
                @Html.CheckBoxFor(model => model.ContactByPhone, new { @id = "myCheckBox", @style = "margin-top: 8px" })
                @Html.ValidationMessageFor(model => model.ContactByPhone)
            </div>
        </div>
        <div class="form-group" id="divContactPhone">
            <div class="col-sm-5">
                @Html.LabelFor(model => model.ContactPhoneNumber, new { @class = "control-label-nobold" })<span class="red">*</span>
            </div>
            <div class="col-sm-4">
                @Html.TextBoxFor(m => m.ContactPhoneNumber, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.ContactPhoneNumber, "", new { @style = "color:Red" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-5 text-left">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script src="~/Scripts/mvcfoolproof.unobtrusive.min.js"></script>
    <script src="~/Scripts/MvcFoolproofJQueryValidation.min.js"></script>
    <script src="~/Scripts/MvcFoolproofValidation.min.js"></script>
    <script>
        $("#divContactPhone").hide();
        $("input[type=checkbox]").on("click", function () {
            $("#divContactPhone").toggle('show');
        });
    </script>
}

Note: I used jquery to control the hidden div element.

Lin
  • 15,078
  • 4
  • 47
  • 49
  • 1
    Can you please share the project? I am getting `uncaught referenceerror sys is not defined` in jquery 1.10.2 after adding these libraries. – James123 Dec 26 '13 at 15:31
  • You mean to upload the project to somewhere? – Lin Dec 26 '13 at 15:58
  • You need to use NuGet to download "MVC Foolproof Validation" and "Mvc Extensions.Foolproof". You might be missing one of them. – Lin Dec 26 '13 at 16:03
  • thanks for that. this time I am getting `Uncaught TypeError: Cannot read property 'ValidatorRegistry' of undefined` in jquery. Please my references on the page `http://i.stack.imgur.com/vBoJ6.png`. I was loading this checkbox on fancybox on link click. So fancybox not all loading if I add this. – James123 Dec 26 '13 at 16:42
  • I'm not sure where exactly the problem exists. But I can give you some suggestions. 1) make sure you enabled ClientValidationEnabled in Web.config file. 2) If you don't need MicrosoftAjax.js file, don't use it. 3) sometimes the order of JS files matter, make sure the order is correct. 4) use BundleConfig class to manage your JS files for different type of JS files. this will reduce your page loading time. 5) See this link, it may help you: http://blogs.msdn.com/b/simonince/archive/2010/06/11/adding-client-side-script-to-an-mvc-conditional-validator.aspx – Lin Dec 26 '13 at 16:57
  • 3
    It's worth noting that the [Codeplex docs](http://foolproof.codeplex.com/) seem to indicate that you only load the `mvcfoolproof.unobtrusive.js` file, so this suggestion is likely incorrect. – Tieson T. Mar 15 '14 at 04:35
  • I'm getting this error as well. As @TiesonT. suggested, the codeplex only mentions the need to reference mvcfoolproof.unobtrusive.js. Adding the other files doesn't help. – howlee Oct 03 '14 at 06:37