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?
Check out MVC Foolproof validation. It has data annotation in model like RequiredIf (dependent Property, dependent value) if I remember correctly. You can download Foolproof from Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution if using VS2017. Reference mvcfoolproof.unobtrusive.min.js in addition to the jquery files.
I can't give you exactly what you're asking for, but have you considered something like the following?
Justification being the
int DocumentType
variable. You could replace this with using concrete subclass types for each "type" of document you need to deal with. Doing this gives you much better control of your property annotations.It also appears that only some of your properties are needed in different situations, which could be a sign that your document class is trying to do too much, and supports the suggestion above.
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 neithername
orname2
are supplied as long asDocumentType
is not equal to 1 or 2Check out Fluent Validation
https://www.nuget.org/packages/FluentValidation/
Project Description A small validation library for .NET that uses a fluent interface and lambda expressions for building validation rules for your business objects.
https://github.com/JeremySkinner/FluentValidation
RequiredIf validation attribute
I've written a
RequiredIfAttribute
that requires a particular property value when a different property has a certain value (what you require) or when a different property has anything but a specific value.This is the code that may help:
Conditionally required property using data annotations