Reputation: 61
My question is similar to this one.
class WorkFlowData
{
[Required]
public InputData Data{ get; set; }
public String Whatever { get; set; }
}
class GenericWorkFlowData
{
public InputData Data{ get; set; }
public String Whatever { get; set; }
}
class InputData
{
public int ObjectID { get; set; }
public string Name { get; set; }
}
I want to achieve that the property ObjectID to be required.
However, I would like to use the RequiredAttribute at class level and not property level. The validation should consider the property ObjectID of class InputData.
As you can see it above, it is not always that the ObjectID should be validated or set it as required, depending on which class InputData is being called, there should be a validation or not.
Upvotes: 1
Views: 1487
Reputation: 1004
If you need programmatic validation, implement IValidatableObject.
public class Blog : IValidatableObject
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
public string BloggerName { get; set; }
public DateTime DateCreated { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Title == BloggerName)
{
yield return new ValidationResult
("Blog Title cannot match Blogger Name", new[] { "Title", “BloggerName” });
}
}
}
Code from MSDN: https://learn.microsoft.com/en-us/ef/ef6/saving/validation
Upvotes: 2