小编典典

定制验证属性,用于将我的属性的值与模型类中另一个属性的值进行比较

c#

我想创建一个自定义验证属性,在该属性中我想将我的属性的值与模型类中另一个属性的值进行比较。例如,我在模型类中有:

...    
public string SourceCity { get; set; }
public string DestinationCity { get; set; }

我想创建一个自定义属性来像这样使用它:

[Custom("SourceCity", ErrorMessage = "the source and destination should not be equal")]
public string DestinationCity { get; set; }
//this wil lcompare SourceCity with DestinationCity

我如何到那里?


阅读 280

收藏
2020-05-19

共1个答案

小编典典

这是获取其他属性值的方法:

public class CustomAttribute : ValidationAttribute
{
    private readonly string _other;
    public CustomAttribute(string other)
    {
        _other = other;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_other);
        if (property == null)
        {
            return new ValidationResult(
                string.Format("Unknown property: {0}", _other)
            );
        }
        var otherValue = property.GetValue(validationContext.ObjectInstance, null);

        // at this stage you have "value" and "otherValue" pointing
        // to the value of the property on which this attribute
        // is applied and the value of the other property respectively
        // => you could do some checks
        if (!object.Equals(value, otherValue))
        {
            // here we are verifying whether the 2 values are equal
            // but you could do any custom validation you like
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }
}
2020-05-19