sp9
sp9

Reputation: 755

RequireIf conditional validation in MVC

In my model I have the below property

public int? Data
{
    get;
    set;
}

and using @Html.TextBoxFor(m => m.Data) I am adding it in the view. I have another property in the model

public DateTime? DateData { get; set; }

which I display using @Html.FormTextBoxFor(m => m.DateData, new { id = "DateData " })

How can I use the RequiredIf attribute or any other method to make the DateData required if the value of Data is not 0. So anytime the value of Data is not zero or null I want the DateData to be a required property.

Upvotes: 0

Views: 226

Answers (1)

meda
meda

Reputation: 45500

Add another property

public bool DataIsNotZero 
{
   get
   {
       return Data !=0 || Data !=null ;
   }
}

Then using RequiredIf

[RequiredIf("DataIsNotZero", true, ErrorMessage = "Required!!!")]
public DateTime? DateData { get; set; }

Please note:

As pointed out in the comments, Required if is not a built-in attribute. You need to download and import third party library:

MVC Foolproof Validation

Upvotes: 1

Related Questions