0

我看到 Castle 验证器可以使用长度验证属性。

    [ValidateLength(6, 30, "some error message")]
    public string SomeProperty { get; set; }

我正在尝试查找仅 MinLength 属性有没有办法使用开箱即用的属性来做到这一点?

到目前为止,我的想法是实现 AbstractValidationAttribute

public class ValidateMinLengthAttribute : AbstractValidationAttribute

并使其 Build 方法返回 MinLengthValidator,然后在 SomeProperty 上使用 ValidateMinLength

public class MinLengthValidator : Castle.Components.Validator.IValidator

有没有人有一个完全实现的 IValidator 的例子或者知道这样的文档存在哪里?我不确定所有方法和属性都在期待什么。

谢谢

4

1 回答 1

4

如果其他人需要这方面的帮助,我将发布我提出的实现:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Parameter, AllowMultiple = true)]
public class ValidateMinLengthAttribute : AbstractValidationAttribute
{
    private IValidator validator;

    public ValidateMinLengthAttribute(int minLength)
    {
        validator = new MinLengthValidator(minLength);
    }

    public ValidateMinLengthAttribute(int minLength, string errorMessage) : base(errorMessage)
    {
        validator = new MinLengthValidator(minLength);
    }

    public override IValidator Build()
    {
        ConfigureValidatorMessage(validator);

        return validator;
    }
}

[Serializable()]
public class MinLengthValidator : AbstractValidator
{
    private int _minLength;
    private const string defaultErrorMessage = "Field must contain at least {0} characters";

    public MinLengthValidator(int minLength)
    {
        _minLength = minLength;
    }

    public override bool IsValid(object instance, object fieldValue)
    {
        if (fieldValue == null) return true;

        return fieldValue.ToString().Length >= _minLength;
    }

    public override bool SupportsBrowserValidation
    {
        get { return true; }
    }

    public override void ApplyBrowserValidation(BrowserValidationConfiguration config, InputElementType inputType, IBrowserValidationGenerator generator, System.Collections.IDictionary attributes, string target)
    {
        base.ApplyBrowserValidation(config, inputType, generator, attributes, target);

        string message = string.Format(defaultErrorMessage, _minLength);
        generator.SetMinLength(target, _minLength, ErrorMessage ?? message);
    }

    protected override string BuildErrorMessage()
    {
        return string.Format(defaultErrorMessage, _minLength);
    }
}
于 2010-04-22T02:11:29.740 回答