UPDATE It seems I have misunderstood the question. As the other answer has already pointed out, you could implement the IValidatableObject for achieving this. Something like:
public class YourModelName : IValidatableObject
{
[StringLength(20)]
public string Number{ get; set; }
[Required]
public DateTime? TimeOf { get; set; }
public bool HasType { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (TimeOf != null && HasType)
Validator.TryValidateProperty(this.Number,
new ValidationContext(this, null, null) { MemberName = "Number" },
results);
if (TimeOf == null)
results.Add(new ValidationResult("Date Time must have a value"));
if (!HasType)
results.Add(new ValidationResult("Must be true"));
return results;
}
}
OLD ANSWER:
You could write your custom validator for more complex validation conditions. Something like:
public class SomeCustomValidator : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string number = value as string;
if (value == null) throw new InvalidOperationException("Can only be used on string properties");
if (!value.IsEmpty && value.Length <= 20)
{
return ValidationResult.Success;
}
return new ValidationResult("Name must be a non-empty string smaller than 20 chars"));
}
}
And for HasType, another custom one:
public class IsTrueAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null) return false;
if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");
return (bool) value == true;
}
}
And on TimeOf you could use the required attribute to make sure it has a value:
[Required(ErrorMessage="Must have value")]
public DateTime? TimeOf {get;set;}
And use the custom attributes on the other two:
[SomeCustomValidator(ErrorMessage="Error msg...")]
public string Number {get;set;}
[IsTrueAttribute(ErrorMessage="Must be true")]
public bool HasType {get;set;}