If I am not mistaken, only primitive types can be passed as parameters type to a custom made ValidationAttribute
(string
for example):
public class AttributeNameValidation : ValidationAttribute
{
public string AttributeName { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (MyProperty == value.ToString())
{
return new ValidationResult($"Attribute with the name '{value.ToString()}' already exist.", new[] { validationContext.MemberName });
}
return null;
}
}
and using it like this:
[Required]
[AttributeNameValidation(AttributeName = "MyAttribute")]
public string Name { get; set; }
But what if we want to pass a non-primitive type to the custom made ValidationAttribute
? For example how I can pass an instance of this object into AttributeNameValidation
? (While keeping the outer property non static)
public class Attribute
{
public string Name { get; set; }
public string Type { get; set; }
}
public Attribute myAttrib = new Attribute {Name = "Price", Type = "int"};
supposing that a property of type Attribute
is created in the AttributeNameValidation
with the name: Attrib
(public Attribute Attrib { get; set; }
), the IntelliSense complains that:
[Required]
[AttributeNameValidation(Attrib = myAttrib)]
public string Name { get; set; }