RobertDev22
RobertDev22

Reputation: 129

Custom Validation Attribute: Comparing one property to another property's inner property

I have a class StarActivityModel, and I want to validate that the inputted value for StarChange, is less than the Client's property of StarCount. To do this I have attempted to create a Custom Validation Attribute but am having trouble getting the StarCount value.

public class StarActivityModel : BaseModel
{
    [Display(Name = "App User")]
    public Client? Client { get; set; }

    [Display(Name = "Star Change")]
    public int? StarChange { get; set; }
}

public class Client 
{
    public virtual int StarCount { get; set; }

}

My attempt at a custom Validation Attribute

[AttributeUsage(AttributeTargets.Property)]
public class ValidStarChangeAttribute : ValidationAttribute
{
    private readonly string _comparisonProperty;

    public ValidStarChangeAttribute(string testedPropertyName)
    {
        _comparisonProperty = testedPropertyName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var propertyInfo = validationContext.ObjectType.GetProperty(_comparisonProperty);
        
        //Compare passed StarCount and Client starcount
        if((int) value > //Somehow get client StarCount)
            return //Code an error message

        return ValidationResult.Success;
    }

}

 

Upvotes: 1

Views: 3512

Answers (1)

Ruikai Feng
Ruikai Feng

Reputation: 11631

You could search the ValidationContex class for the method and property you need in custom model validation. enter image description here

I modified your codes and it seems work well

Codes:

public class ValidStarChangeAttribute : ValidationAttribute
    {
        
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            StarActivityModel staractivemodel = (StarActivityModel)validationContext.ObjectInstance;
            if (value != null)
            {
            if((int)value< staractivemodel.Client.StarCount)
            {
                return ValidationResult.Success;
            }
            }
            return new ValidationResult("error");
        }

    }

Result: Result

Upvotes: 2

Related Questions