Its a kind of odd why MinLength data annotation is not workling client side out of the box. The RequiredFieldValidator does.
So i tried a lot and finally i found the solution to get this working. We need to create an own implementation of the StringLengthAttribute and overwrite a method that returns the client validation rules of the mvc inbuild adapter. Using this way no bad javascript magic is needed, because mvc supports the StringLength validation.
public sealed class StringLenAttribute : StringLengthAttribute, IClientValidatable
{
public StringLenAttribute(int minimumLength, int maximumLength = 50)
: base(maximumLength)
{
MinimumLength = minimumLength;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata, ControllerContext context)
{
var adapt = new StringLengthAttributeAdapter(metadata, context, this);
return adapt.GetClientValidationRules();
}
}
For completeness I show my implementation for client side enabled email adress validation. It also implements the IClientValidatable.GetClientValidationRules() but it works without creating an adapter.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class EmailAttribute : RegularExpressionAttribute, IClientValidatable
{
public EmailAttribute()
: base(
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")
{
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule()
{
ValidationType = "email",
ErrorMessage = ErrorMessage
};
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if (!base.IsValid(value))
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
}
1 Kommentare:
your post is very interesting. I like it very much. It is very helpful and useful for me. Thanks for share this valuable post.
Post a Comment