1

I would like to replace the default error message for for example RequiredAttribute or RegularExpressionAttribute with my own messages, so that I wouldn't need to specify the explicit ErrorMessage at attribute usage.

EDIT: Last part of the sentence means that I'm aware of the ability to specify my own ErrorMessage at attribute usage, and I would like to avoid it for keeping the project DRY.

Is it possible somehow? I haven't found any related property in the .NET library, and I currently have no idea how I could replace the .NET resources where the default messages are stored.

Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93

1 Answers1

1

Just create your own version of the [Required] attribute that has a default message that you want. If you only want to use a custom error message have it inherit from RequiredAttribute so you can take advantage of the same IsValid logic

public class MyRequired : RequiredAttribute
{
    public MyRequired()
    {
        this.ErrorMessage = "Custom Validation Error Message.";
    }
}

If you need even finer control over other validation behaviors, you can create your own DataAnnotation Attributes.

public class MyRequired : ValidationAttribute
{
    public MyRequired() : base("My Custom Message")
    {

    }

    public override bool IsValid(object value)
    {
        //Your custom validation logic
        return (value != null);
    }
}
Community
  • 1
  • 1
ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
  • Thanks, I knew about this way but I hoped for a nicer one. Anyway why not just not override the IsValid function? – Zoltán Tamási May 01 '15 at 13:43
  • ? `IsValid` is being overridden. I don't understand what you're saying. – ryanyuyu May 01 '15 at 13:46
  • It's easier to override the relevant attribute (e.g. RequiredAttribute) rather than ValidationAttribute where you also need to implement `IsValid` again. – Richard May 01 '15 at 13:49
  • Ah, I didn't notice that you've inherited from ValidationAttribute, I thought you've inherited from RequiredAttribute and that's why I questioned why you've overridden the IsValid method. Sorry for the not too correct english sentence too :) – Zoltán Tamási May 01 '15 at 13:51
  • Ok yes I see what you mean, give me a few minutes to update. This will currently work, but your suggestions are another improvement. – ryanyuyu May 01 '15 at 13:52
  • @Richard thanks for the extra advice. Updated answer. – ryanyuyu May 01 '15 at 14:03