I have a model class that uses a custom validator as shown in following code.
public class Model1
{
[ApplicationIdentifierValidator()]
public Guid ApplicationIdentifier { get; set; }
public string ApplicationName { get; set; }
public string ApplicationType { get; set; }
}
public class ApplicationIdentifierValidator: ValidationAttribute
{
public ApplicationIdentifierValidator() { }
protected override ValidationResult IsValid(object value, ValidationContext context)
{
Model1 model = (Model1)(context.ObjectInstance);
Guid ApplicationIdentifier = model.ApplicationIdentifier;
// Validate ApplicationIdentifier value
return ValidationResult.Success;
}
}
Now I have added another model class, that need to use same validator.
public class Model2
{
[ApplicationIdentifierValidator()]
public Guid ApplicationIdentifier { get; set; }
public Guid SystemIdentifier { get; set; }
}
Problem is when ApplicationIdentifierValidator is used in context of Model2, it throws exception when casting to Model1
Model1 model = (Model1)(context.ObjectInstance);
Any ideas what could be better approach to re-use same validator?
You could use inheritance. The basic OO design should serve your exact need.
By having your two models inherit from ModelBase, your validation code can cast the object to ModelBase and use the shared property.