yu_sha
yu_sha

Reputation: 4410

Unobtrusive validation for integers with MVC3 and jQuery

Unobtrusive validation does not distinguish between data types. There's only 'number' validation that MVC adds to all numeric fields.

This has an unwanted effect of 1.2345 being a valid integer. When you submit, MVC binder cannot parse the value. So instead of getting a client-side error you get it from server.

What is the best way of solving this? Are there existing solutions?

Upvotes: 2

Views: 3507

Answers (1)

yu_sha
yu_sha

Reputation: 4410

Ok, here's what I did.

Wrote my own EditorTemplate for Int32 (Views/Shared/EditorTemplates/Int32.cshtml):

@model int?           
@Html.TextBox("", Model.HasValue ? Model.Value.ToString() : "", new { data_val_integer = "Field must be an integer" }) 

Added a validation adapter (run this on $(document).ready:)

jQuery.validator.addMethod('integer',
    function (value, element, params) {
        return String.IsNullOrEmpty(value) || isInteger(value);
    });

jQuery.validator.unobtrusive.adapters.add("integer", [],
    function (options) {
        options.rules['integer'] = {};
        options.messages['integer'] = options.message;
    });

Wrote Javascript function isInteger that looks like this

function isInteger(value) {
    return parseInt(value, 10) == value;
}

Now integer fields give a nice message "Field must be an integer" if you type anything with decimal dot in it.

Will be glad to hear of a better way.

Upvotes: 5

Related Questions