如何使用新的错误消息创建自定义MaxLength和Required验证,逻辑保持不变
本文关键字:验证 Required 何使用 错误 消息 MaxLength 自定义 创建 | 更新日期: 2023-09-27 18:17:30
[MaxLength(45, ErrorMessage = Translations.Attribute.MAX_LENGTH)]
[Required(ErrorMessage = Translations.Attribute.REQUIRED)]
如何使用默认翻译消息创建自定义Required
和MaxLength
验证。我可以简单地重写它并只更改errorMessage吗?
我只想写
[MyMaxLength(45)]
[MyRequired]
所需创建的解决方案:
public class MyRequiredAttribute : RequiredAttribute
{
public override string FormatErrorMessage(string name)
{
return string.Format("Polje {0} je obvezno", name);
}
}
你应该能够从MaxLengthAttribute
,或任何其他属性你正在使用…
public class MyMaxLengthAttribute : MaxLengthAttribute
{
public MyMaxLengthAttribute(int length) : base(length)
{
ErrorMessage = Translations.Attribute.MAX_LENGTH;
}
// other ctors/members as needed
}
对于任何正在使用MVC并想要自定义或本地化MaxLength错误消息的人。
1)创建自己的MaximumLengthAttribute,从MaxLength派生,使用一个资源文件。
2)创建一个MaximumLengthValidator,利用MaxLength规则。
3)在Application_Start
中注册MaximumLenghtAttribute和Validator4)用MaximumLength(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);
}
}
和
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;
}
}
和Application_Start…
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaximumLengthAttribute), typeof(MaximumLengthValidator));
在这种情况下,我创建的AppMaxLength属性是从MaxLengthAttribute继承的,MaxLength不固定,它可以在webconfig或DBConfig上更改,如果你想。
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;
}
}
和应用:
[AppMaxLength("NotFixedCodeLength", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "MsgMaxLength")]
public string Code { get; set; }
webconfig的配置信息:
appSettings标签插入键
<add key="NotFixedCodeLength" value="10" />
对不起,我的英文不好。=)) using System.ComponentModel.DataAnnotations;
[Required(ErrorMessage = "This field is required!!!")]
[MaxLength(30, ErrorMessage = "Max number of characters is 30 duh!")]
public string FirstName { get; set; }