MVC foolproof validations with mvc4

2.5k views Asked by At

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>
1

There are 1 answers

3
bsting On

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")