senzacionale
senzacionale

Reputation: 20906

HowTo create custom MaxLength and Required validation with new error message, logic stays the same

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

How can I create custom Required and MaxLength validation with default translated message. Can I simply override it and change just errorMessage?

I just want to write

[MyMaxLength(45)]
[MyRequired]

Solution for requied founded:

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

Upvotes: 3

Views: 5344

Answers (4)

tdman1325
tdman1325

Reputation: 240

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

Upvotes: 0

Tony Hung
Tony Hung

Reputation: 54

In this case I created the AppMaxLength attribute was inheriting from MaxLengthAttribute, the MaxLength not fixing, it can be change on the webconfig or DBConfig if you want.

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 applying:

    [AppMaxLength("NotFixedCodeLength", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "MsgMaxLength")]       
    public string Code { get; set; }

The config info on webconfig:

appSettings tag insert the key

<add key="NotFixedCodeLength" value="10" />

Sorry my Eng not good. =))

Upvotes: 0

RitchieD
RitchieD

Reputation: 1861

For anyone who is using MVC and wants a custom or localized MaxLength error message.

1) Create your own MaximumLengthAttribute derived from MaxLength that uses a resource file.

2) Create a MaximumLengthValidator that exploits the MaxLength rules.

3) Register your MaximumLenghtAttribute and Validator in the Application_Start

4) Decorate your property with the MaximumLength(45) attribute.

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

Upvotes: 2

dav_i
dav_i

Reputation: 28097

You should be able to just derive from MaxLengthAttribute, or whatever other attributes you are using...

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

    // other ctors/members as needed
}

Upvotes: 5

Related Questions