1

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;
    }

}

 
RobertDev22
  • 119
  • 7

1 Answers1

2

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

Ruikai Feng
  • 6,823
  • 1
  • 2
  • 11