将自定义参数传递给ValidationAttribute

Mik*_*ole 13 asp.net-mvc-4

我构建了一个自定义ValidationAttribute,因此我可以验证系统中的唯一电子邮件地址.但是,我想以某种方式传入自定义参数,以便为我的验证添加更多逻辑.

public class UniqueEmailAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        //I need the original value here so I won't validate if it hasn't changed.
        return value != null && Validation.IsEmailUnique(value.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*ver 36

像这样?

public class StringLengthValidatorNullable : ValidationAttribute
{
    public int MinStringLength { get; set; }
    public int MaxStringLength { get; set; }

    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return false;
        }
        var length = value.ToString().Length;

        if (length < MinStringLength || length >= MaxStringLength)
        {
            return false;
        }
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用:

[StringLengthValidatorNullable(MinStringLength = 1, MaxStringLength = 16)]
public string Name {get; set;}
Run Code Online (Sandbox Code Playgroud)


typ*_*n04 5

您还可以传递属于同一模型中其他属性的参数。

创建自定义验证属性:

public class SomeValidationAttribute : ValidationAttribute
{
    //A property to hold the name of the one you're going to use.
    public string OtherProperty { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //Get the value of the property using reflection.
        var otherProperty = validationContext.ObjectType.GetProperty(OtherProperty);
        var otherPropertyValue = (bool)otherProperty.GetValue(validationContext.ObjectInstance, null);

        if (value != null && otherPropertyValue)
        {
            return ValidationResult.Success;
        }

        return new ValidationResult("Invalid property message.");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后传递您要使用的属性的名称。

    public class RequestModel 
    {
        public bool SomeProperty { get; set; }

        [SomeValidation(OtherProperty = "SomeProperty")]
        public DateTime? StartDate { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)