I have a class like this:
public class Document
{
public int DocumentType{get;set;}
[Required]
public string Name{get;set;}
[Required]
public string Name2{get;set;}
}
Now if I put a [Required]
data annotation on the Name
and Name2
properties, then everything is ok and if Name
or Name2
are empty, validation will throw an error.
But I want Name
field only to be required if DocumentType
is equal to 1
and Name2
only required if DocumentType
is equal to 2 .
public class Document
{
public int DocumentType{get;set;}
[Required(Expression<Func<object, bool>>)]
public string Name{get;set;}
[Required(Expression<Func<object, bool>>)]
public string Name2{get;set;}
}
but I know I can't, it causes an error. What should I do for this requirement?
Out of the box I think this is still not possible.
But I found this promising article about Mvc.ValidationToolkit (also here, unfortunately this is only alpha, but you probably could also just extract the method(s) you need from this code and integrate it on your own), it contains the nice sounding attribute RequiredIf
which seems to match exactly your cause:
install-package Microsoft.AspNet.Mvc
)using Mvc.ValidationToolkit;
[RequiredIf("DocumentType", 2)]
or [RequiredIf("DocumentType", 1)]
, so objects are valid if neither name
or name2
are supplied as long as DocumentType
is not equal to 1 or 2