1

I have tried to use Requiredif and RequiredifTrue, but both are not working. below is the my code. when I make the value of IsmedicalInsurance to true/false, both other does'nt work.

[Required(ErrorMessage="Please update about medical insurance")]
    public bool? IsMedicalInsurance { set; get; } 

[RequiredIf("IsMedicalInsurance", true, ErrorMessage = "Enter Primary Insuracne Name")]
    public string PrimaryInsurance { set; get; }

[RequiredIfTrue("IsMedicalInsurance", ErrorMessage = "Enter Id number")]
     public string IDnumber { set; get; }

view code.

<label class="radio-inline">
@Html.RadioButtonFor(m => m.IsMedicalInsurance, true, new { id="rdhaveinsur"}) Yes  
</label>
<label class="radio-inline">
  @Html.RadioButtonFor(m => m.IsMedicalInsurance, false, new { id="rdhaveno"})No
  @Html.ValidationMessageFor(m => m.IsMedicalInsurance)
 </label>


<div class="col-sm-7">
  @Html.TextBoxFor(m => m.PrimaryInsurance, new { @class = "form-control", id =  "txtInsurance" })
@Html.ValidationMessageFor(m => m.PrimaryInsurance)
</div>

<div class="col-sm-7">
 @Html.TextBoxFor(m => m.IDnumber, new { @class = "form-control", id = "txtIdNumber" })
 @Html.ValidationMessageFor(m => m.IDnumber)
 </div>
Muhammad Danish
  • 111
  • 1
  • 6
  • 20
  • Can you please post your view code? – Mox Shah Nov 13 '14 at 04:45
  • The possible issue is the use of radio buttons and/or the fact you don't have a radio button for a `null` value. Try using `@EditorFor(m => m.IsMedicalInsurance)` instead of radio buttons (it will render a drop down with 3 options "Not set", "True" and "False") –  Nov 13 '14 at 05:29

1 Answers1

0

Why you need to have IsMedicalInsurance to be nullable since the value is either true of false and shouldn't be null? I have try your code and it is working with IsMedicalInsurance change to bool instead of bool

Update

Have you loaded below scripts?

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/Scripts/mvcfoolproof.unobtrusive.min.js")
bsting
  • 154
  • 4
  • If I remove nullable then If user does'nt select the radio button for medical insurance then binded IsmedicalInsurance property does not give error that "please update about medical insurance". Also I have tried by removing bool?, but still other fields are not going to be validated. – Muhammad Danish Nov 13 '14 at 04:43
  • I was using check box in my testing. will try with radio button then – bsting Nov 13 '14 at 04:46
  • @MuhammadDanish, is the server side validation work at your side? I have the problem where client side validation is not working, however, after adding mvcfoolproof.unobtrusive.min.js, it works as expected. – bsting Nov 13 '14 at 10:05