Min Length Custom AbstractValidationAttribute and Implementing Castle.Components.Validator.IValidator
I see with the Castle validators I can use a length validation attribute.
[ValidateLength(6, 30, "some error message")]
public string SomeProperty { get; set; }
I am trying to find a MinLength only attribute is there a way to do this with the out of the box attributes?
So far my idea is implementing开发者_高级运维 AbstractValidationAttribute
public class ValidateMinLengthAttribute : AbstractValidationAttribute
and making its Build method return a MinLengthValidator, then using ValidateMinLength on SomeProperty
public class MinLengthValidator : Castle.Components.Validator.IValidator
Does anyone have an example of a fully implemented IValidator or know where such documentation exists?? I am not sure what all the methods and properties are expecting.
Thanks
In case anyone else needs help with this I will post the implementation I came up with:
[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);
}
}
精彩评论