Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I customize the unobtrusive validation JQuery messages in ASP NET MVC?

I have a form, and when it does the unobtrusive validtaion I want it to show:

This message: "Please enter a value."

Instead of this message: "This Field is required."

I tried adding this at the end of my jquery.validate.unobtrusive.js file

(function ($) {
   $.extend($.validator.messages, {
     required: "Please enter a value."
   }); 
}(jQuery));

But it's just not working.

I also trying modifying directly the "messages" variable in jquery.validate.js file but it is not working either.

Could you please tell me how can I get this done?

like image 953
Laggel Avatar asked Oct 14 '13 16:10

Laggel


People also ask

What is unobtrusive JavaScript validation in MVC?

An unobtrusive validation in jQuery is a set of ASP.Net MVC HTML helper extensions.By using jQuery Validation data attributes along with HTML 5 data attributes, you can perform validation to the client-side.

What is validator unobtrusive parse?

validator. unobtrusive. parse(selector) method to force parsing. This method parses all the HTML elements in the specified selector and looks for input elements decorated with the [data-val=true] attribute value and enables validation according to the data-val-* attribute values.


1 Answers

If you're using the data annotation attributes and don't want to customize the message for each one (which, it appears by one of your comments that this is the case), I can see two options:

1) Create your own data annotation attribute and set a default message, and change all instances of [Required] to your new attribute.

2) You can try it in jQuery:

// reset the form's validator
$("form").removeData("validator");

// change the text on each required attribute
$(":input[data-val-required]").attr("data-val-required", "Please enter a value");

// reapply the form's validator
$.validator.unobtrusive.parse(document);

I tried this javascript in Chrome's console and everything seemed to work ok. The reason why you need to do this is because 1) the validation rules are cached by the browser so you need to clear them out (See this answer for more information). And 2) all of the error messages are in the html markup once the page is rendered, so that's where you need to change the validation messages.

like image 143
hawkke Avatar answered Sep 17 '22 13:09

hawkke