How to create custom MaxLength and mandatory validation with new error message, logic remains the same
[MaxLength(45, ErrorMessage = Translations.Attribute.MAX_LENGTH)]
[Required(ErrorMessage = Translations.Attribute.REQUIRED)]
How to create custom validation Required
and MaxLength
with default translation. Can I just override it and only change the errorMessage?
I just want to write
[MyMaxLength(45)]
[MyRequired]
Solution for an informed:
public class MyRequiredAttribute : RequiredAttribute
{
public override string FormatErrorMessage(string name)
{
return string.Format("Polje {0} je obvezno", name);
}
}
source to share
You should be able to just fetch from MaxLengthAttribute
or whatever other attributes you use ...
public class MyMaxLengthAttribute : MaxLengthAttribute
{
public MyMaxLengthAttribute(int length) : base(length)
{
ErrorMessage = Translations.Attribute.MAX_LENGTH;
}
// other ctors/members as needed
}
source to share
For anyone using MVC and want a custom or localized MaxLength error message.
1) Create your own MaximumLengthAttribute derived from MaxLength which is using the resource file.
2) Create a MaximumLengthValidator that uses MaxLength rules.
3) Register your MaximumLenghtAttribute and Validator in Application_Start
4) Decorate your object with the MaximumLength attribute (45).
using System;
using System.ComponentModel.DataAnnotations;
public class MaximumLengthAttribute : MaxLengthAttribute
{
/// <summary>
/// MaxLength with a custom and localized error message
/// </summary>
public MaximumLengthAttribute(int maximumLength) : base(maximumLength)
{
base.ErrorMessageResourceName = "MaximumLength";
base.ErrorMessageResourceType = typeof(Resources);
}
}
and.....
using System.Collections.Generic;
using System.Web.Mvc;
public class MaximumLengthValidator : DataAnnotationsModelValidator
{
private string _errorMessage;
private MaximumLengthAttribute _attribute;
public MaximumLengthValidator(ModelMetadata metadata, ControllerContext context, MaximumLengthAttribute attribute)
: base(metadata, context, attribute)
{
_errorMessage = attribute.FormatErrorMessage(metadata.GetDisplayName());
_attribute = attribute;
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule
{
// Uses MVC maxlength validator (but with a custom message from MaximumLength)
ErrorMessage = this._errorMessage,
ValidationType = "maxlength"
};
rule.ValidationParameters.Add("max", _attribute.Length);
yield return rule;
}
}
and in Application_Start ...
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaximumLengthAttribute), typeof(MaximumLengthValidator));
source to share
In this case, I created an AppMaxLength attribute that inherits from MaxLengthAttribute, MaxLength does not fix it, it can be changed in webconfig or DBConfig if you like.
public class AppMaxLengthAttribute : MaxLengthAttribute, IClientValidatable
{
public AppMaxLengthAttribute(string configName)
: base(int.Parse(WebConfigurationManager.AppSettings[configName]))
{
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "maxlength"
};
rule.ValidationParameters.Add("max", this.Length);
yield return rule;
}
}
And the application:
[AppMaxLength("NotFixedCodeLength", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "MsgMaxLength")]
public string Code { get; set; }
Configuration information in webconfig:
AppSettings tag insert key
<add key="NotFixedCodeLength" value="10" />
Sorry, my Eng is not very good. =
source to share