MVC 5 Customer side validation

Asked

Viewed 1,265 times

6

I’m having trouble validating dates and numbers on the client side using MVC 5 Asp.net. Examples and tutorials I find on the internet are all outdated.

I made the modifications according to this reply and the validation began to work correctly in Portuguese, but now occurs on the side of server side.

I installed both packages:

  1. jquery-globalize
  2. jquery.validation.globalize

On my page include these 4 references:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

    @Scripts.Render("~/Scripts/jquery.validate.js")
    @Scripts.Render("~/Scripts/jquery.validate.unobstrusive.js")
    @Scripts.Render("~/Scripts/globalize.js")
    @Scripts.Render("~/Scripts/jquery.validate.globalize.js")
}

And on the web.config:

<system.web>
    <!-- outros parametros -->
    <globalization culture="pt-BR" uiCulture="pt-BR" />
</system.web>

Obs: I’m following this tutorial link

Would someone have some more complete example, or could explain to me what is missing?

2 answers

1

It works. Just change the code in the file BundleConfig, besides adding the files methods_pt and helper.js

public static void RegisterBundles(BundleCollection bundles)
{

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*",
                        "~/Scripts/methods_pt.js",
                        "~/Scripts/helper.js"));
}

0

You must respect this sequence:

1 - jquery.unobtrusive-ajax.js // If you own Ajax

2 - jquery.validate.js

3 - jquery.validate.unobtrusive.js

4 - globalize.js

5 - jquery.validate.globalize.js

6 - methods en.js // This you will create and insert by penultimate

7 - helper.js // This you will create and insert last

Add the following code in methods-en.js

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);
    }
});

Add the following code to the helper.js:

$(document).ready(function () {

    //Filtro Decimal para aceitar vírgula
    $.validator.methods.range = function (value, element, param) {
        var globalizedValue = value.replace(",", ".");
        return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
    }

    $.validator.methods.number = function (value, element) {
        return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.