Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"The field width must be a number." at client side

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.

like image 864
wuwen218 Avatar asked Dec 29 '10 09:12

wuwen218


3 Answers

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.

like image 60
Pavel Surmenok Avatar answered Oct 10 '22 04:10

Pavel Surmenok


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.

like image 20
Luca Domenichini Avatar answered Oct 10 '22 04:10

Luca Domenichini


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

 [RegularExpression("([0-9]+)", ErrorMessageResourceType = typeof(ErrorMessage), ErrorMessageResourceName = "NumberInvalid")]
like image 1
Nick Avatar answered Oct 10 '22 04:10

Nick