Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize validation attribute error message?

Tags:

At the moment I have a custom validation attribute called ExistingFileName (below) but i have given it error messages to display

    protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
    {
        if (value!=null)
        {
            string fileName = value.ToString();
            if (FileExists(fileName))
            {
                return new ValidationResult("Sorry but there is already an image with this name please rename your image");
            }
            else
            {
                return ValidationResult.Success;
            }  
        }
        else
        {
            return new ValidationResult("Please enter a name for your image");
        }
    }

I have implemented it like so:

[ExistingFileName]
public string NameOfImage { get; set; }

Im sure theres a way to define the error message when setting the attribute like below:

[ExistingFileName(errormessage="Blah blah blah")]
public string NameOfImage { get; set; }

But I'm not sure how? Any help is greatly appreciated

like image 959
Srb1313711 Avatar asked Jul 04 '13 16:07

Srb1313711


People also ask

Which property of Validation attribute is used for displaying the custom error message?

You can provide a custom error message either in the data annotation attribute or in the ValidationMessageFor() method.

How do I create a custom validation attribute?

To create a custom validation attributeUnder Add New Item, click Class. In the Name box, enter the name of the custom validation attribute class. You can use any name that is not already being used. For example, you can enter the name CustomAttribute.

How to display Validation error message in MVC?

You can use the standard ASP.NET MVC ValidationSummary method to render a placeholder for the list of validation error messages. The ValidationSummary() method returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.

What is validation attribute?

Validation attributes let you specify validation rules for model properties. The following example from the sample app shows a model class that is annotated with validation attributes. The [ClassicMovie] attribute is a custom validation attribute and the others are built in.


2 Answers

Instead of returning ValidationResult with a predefined string, try using the ErrorMessage property, or any other custom properties. For example:

private const string DefaultFileNotFoundMessage = 
    "Sorry but there is already an image with this name please rename your image";

private const string DefaultErrorMessage = 
    "Please enter a name for your image";

public string FileNotFoundMessage { get; set; }

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    if (value!=null)
    {
        string fileName = value.ToString();
        if (FileExists(fileName))
        {
            return new ValidationResult(FileNotFoundMessage ??
                                        DefaultFileNotFoundMessage);
        }
        else
        {
            return ValidationResult.Success;
        }  
    }
    else
    {
        return new ValidationResult(ErrorMessage ?? 
                                    DefaultErrorMessage);
    }
}

And in your annotation:

[ExistingFileName(FileNotFoundMessage = "Uh oh! Not Found!")]
public string NameOfImage { get; set; }

If you don't explicitely set a custom message, it will fallback to the predefined constant in your custom attribute.

like image 142
Simon Belanger Avatar answered Oct 12 '22 07:10

Simon Belanger


Have you inherited from ValidationAttribute?

then you don't need to keep it in a separate variable. All error message code is available when you inherit from ValidationAttribute class.

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class ExistingFileNameAttribute : ValidationAttribute
{
    public string FileFoundMessage = "Sorry but there is already an image with this name please rename your image";
    public ExistingFileNameAttribute()
        : base("Please enter a name for your image")
    {            
    }

    public override ValidationResult IsValid(object value)
    {
        if (value!=null)
        {
            string fileName = value.ToString();
            if (FileExists(fileName))
            {
                return new ValidationResult(FileFoundMessage);
            }
            else
            {
                return ValidationResult.Success;
            }  
        }
        else
        {
            return new ValidationResult(ErrorMessage);
        }
    }
}

Now you can use this to validate your fields/properties

[ExistingFileName(ErrorMessage="Blah blah blah", FileFoundMessage = "Blah Bla")]
public string NameOfImage { get; set; }

and if you use it like below.

[ExistingFileName]
public string NameOfImage { get; set; }

then, it will use the default error message set in the constructor of the ExistingFileName attribute

Hope that helps.

like image 24
Amila Avatar answered Oct 12 '22 07:10

Amila