2

I am working with asp.net mvc 5 and want to change validation message text. For example,

[Required]
public string name{ get; set; }

I give required validation and the error message appears as : 'The name field is required.' but i want change 'something my text' for all required validations.

I can do this as

[Required (ErrorMessage="something my text")]

but i don't want repeat this for each parameter.

user2632703
  • 31
  • 1
  • 6
  • 1
    Possible duplicate of [How to change default validation error message in ASP.NET MVC?](http://stackoverflow.com/questions/6214066/how-to-change-default-validation-error-message-in-asp-net-mvc) –  Oct 10 '16 at 12:31
  • Refer this : [How to change the generic validation message text?](http://stackoverflow.com/questions/10317259/mvc3-how-to-change-the-generic-required-validation-message-text) – Divyang Desai Oct 10 '16 at 12:33

2 Answers2

0

I have a simple proposition if you are that much willing to use Required attribute with custom error message then why not use HTML 5 instead for example

@Html.TextBoxFor(m => m.name, 
new { @class = "form-control", placeholder = "name", required="Name is required"})

Other way that I've used In MVC5 is something like this

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {8}      characters long.", MinimumLength = 6)]
    [Display(Name = "User Name")]
    public string UserName{ get; set; }

I hope this helps in any way

Dummy
  • 255
  • 1
  • 4
  • 14
0

I think that this cannot be avoided. We could use reflection (Despite the fact that this is not the best practice), however, attributes are a static part of the assembly, which will be extremely problematic to add dynamically, in addition, it will worsen the understandability of your code.

However, if you still want to give it a try, I suggest you check out this answer: How to add an attribute to a property at runtime

I couldn't make it work, but maybe you can.

Vizel Leonid
  • 456
  • 7
  • 15