Building up on the answer @JotaBe gave, you could use a custom validation attribute on the Model property itself. Something like this :
Conditional Required Attribute
public class ConditionalRequiredAttribute : ValidationAttribute
{
private const string DefaultErrorMessageFormatString
= "The {0} field is required.";
private readonly string _dependentPropertyName;
public ConditionalRequiredAttribute(string dependentPropertyName)
{
_dependentPropertyName = dependentPropertyName;
ErrorMessage = DefaultErrorMessageFormatString;
}
protected override ValidationResult IsValid(
object item,
ValidationContext validationContext)
{
var property = validationContext
.ObjectInstance.GetType()
.GetProperty(_dependentPropertyName);
var dependentPropertyValue =
property
.GetValue(validationContext.ObjectInstance, null);
int value;
if (dependentPropertyValue is bool
&& (bool)dependentPropertyValue)
{
/* Put the validations that you need here */
if (item == null)
{
return new ValidationResult(
string.Format(ErrorMessageString,
validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
}
Applying the Attribute
Here I have a class Movie and the Rating is required depending on the value of RatingIsRequired boolean property which can be set from the server.
public class Movie
{
public bool RatingIsRequired { get; set; }
[ConditionallyRequired("RatingIsRequired"]
public string Rating { get; set; }
}
- With this the
ModelState.IsValid
will return false if RatingIsRequired
set to true and Rating
is empty.
- Also You can write a custom unobtrusive jquery validator to for client enabled validations so that is works like regular
[Required]
attribute.
Let me know if this helps.