Using a custom validation attribute, I'm trying to validate a list of objects. The class is shown below: MyClass
. In the custom attribute, I'm able to covert object value
into a list of objects, but how can I access the properties, Id
and Name
within objects?
I understand I could put the attribute directly on the the MyClass
properties, but I need to check a couple things before validation. First, I need to check if the number of items in the list is greater than one. Then, if the count is greater than one, I need to check if both Id
and Name
are null.
My thought is that it would be easier to validate the entire list in one Attribute. However even if I did place the attributes on the MyClass
properties, I still need to access the values within the list.
If the list is passed as the value
parameter of IsValid
then all list items would be within value. If I put the attributes on the MyClass
properties I would need to get the values another way. I've been able to get single values with the code below, but I'm unable to get a list of values.
Bottom line: I need a way to access all the values within a list either from the object value
parameter or the ValidationContext validationContext
parameter.
Getting a single value (not a list of values):
var property = validationContext.ObjectType.GetProperty("MyProperty");
var value = property.GetValue(validationContext.ObjectInstance, null);
Custom Attribute:
public sealed class ValidateNewSauList : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var myList = value as IList;
}
}
Here is the User defined class:
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
}
The business logic is a bit unclear, so, based on just a qualified guess, the solution could be as following. Assuming that you have a _lst = List<MyClass>
, then you can iterate through the list and apply your validation rules (eg referred to as methods ValidateID()
and ValidateName()
) to both properties:
foreach (MyClass _mc in _lst)
{
ValidateID (_mc.Id);
ValidateName (_mc.Name);
}
Hope this may help. Best regards,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.