如何使用新的错误消息创建自定义MaxLength和Required验证,逻辑保持不变

时间:2014-08-12 08:33:44

标签: c# asp.net-mvc-3

[MaxLength(45, ErrorMessage = Translations.Attribute.MAX_LENGTH)]
[Required(ErrorMessage = Translations.Attribute.REQUIRED)]

如何使用默认翻译邮件创建自定义RequiredMaxLength验证。我可以简单地覆盖它并只更改errorMessage吗?

我只想写

[MyMaxLength(45)]
[MyRequired]

已成立的解决方案:

public class MyRequiredAttribute : RequiredAttribute
    {
        public override string FormatErrorMessage(string name)
        {
            return string.Format("Polje {0} je obvezno", name);
        }
    }

4 个答案:

答案 0 :(得分:5)

您应该能够从MaxLengthAttribute或您使用的任何其他属性派生......

public class MyMaxLengthAttribute : MaxLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = Translations.Attribute.MAX_LENGTH;
    }

    // other ctors/members as needed
}

答案 1 :(得分:2)

对于使用MVC且需要自定义或本地化MaxLength错误消息的任何人。

1)创建自己的MaxLength派生的MaximumLengthAttribute,它使用资源文件。

2)创建一个利用MaxLength规则的MaximumLengthValidator。

3)在Application_Start

中注册MaximumLenghtAttribute和Validator

4)使用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));

答案 2 :(得分:0)

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;
    }
}

答案 3 :(得分:0)

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; }