5

I am using jquery for client side validation together with data annotations. Everything is working fine but I would like to localize a message when a non numeric value is entered in numeric textbox. But for client side validation asp.net mvc is using it's own resource file with key 'ClientDataTypeModelValidatorProvider_FieldMustBeNumeric'.

How can I do?

Thanks.

wuwen218
  • 51
  • 1
  • 2
  • possible duplicate of [asp.net mvc validation must be a number custom error](http://stackoverflow.com/questions/4521254/asp-net-mvc-validation-must-be-a-number-custom-error) – Brian Tompsett - 汤莱恩 Sep 19 '15 at 09:18

3 Answers3

2

Look for solution at the end of this page:

http://jwwishart.wordpress.com/2010/03/22/custom-server-and-client-side-required-validator-in-mvc-2-using-jquery-validate/

I checked this in my MVC 3 RTM project and it works well.

Pavel Surmenok
  • 4,584
  • 4
  • 30
  • 33
  • I implemented what Justin Wishart wrote in the link above about the ClientDataTypeModelValidatorProvider. I used Reflector to get the original class code and pointed the new code to my Localization resource. It's working perfectly in ASP.NET MVC 3. – Leniel Maccaferri Apr 24 '11 at 04:20
2

I had the same problem because I'm Italian and here decimal numbers are formatted with comma instead of dot. So, what in the US is 1,000.12 here is written 1.000,12. That's how I solved, after some searching: MVC3 already includes the script jquery.validate.js/jquery.validate.min.js and that's amazing.

Then I added another script -- methods-it.js -- taken from jquery validate plugin localization folder and changed a little.

jQuery.extend(jQuery.validator.methods, {
    date: function (value, element) {
        return this.optional(element) || /^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);
    },
    number: function (value, element) {
        return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
    },
    range: function (value, element, param) {
        var val = value.replace(",", "#").replace(".", ",").replace("#", ".");
        return this.optional(element) || (val >= param[0] && val <= param[1]);
    }
});

This small code deals with dates (Italian formatting), floating numbers and range of values. It works great, now! Unfortunately this is just a direction and not THE solution, because it has to be corrected for every locale.

dove
  • 20,469
  • 14
  • 82
  • 108
1

I found it easier to just use DataAnnotations on the view model:

 [RegularExpression("([0-9]+)", ErrorMessageResourceType = typeof(ErrorMessage), ErrorMessageResourceName = "NumberInvalid")]
Nick
  • 2,877
  • 2
  • 33
  • 62