среда, 9 октября 2013 г.

Warning - Bad Validation in MVC

Note to support jQuery validation for non-English locales that use a comma (",") for a decimal point, and non US-English date formats, you must include globalize.js and your specificcultures/globalize.cultures.js file(from https://github.com/jquery/globalize ) and JavaScript to useGlobalize.parseFloat. You can get the jQuery non-English validation from NuGet. (Don't install Globalize if you are using a English locale.)
  1. From the Tools menu click Library Package Manager, and then click Manage NuGet Packages for Solution.

  2. On the left pane, select Online(See the image below.)
  3. In the Search Installed packages input box, enter Globalize.

    Click Install. The Scripts\jquery.globalize\globalize.js  file will be added to your project. TheScripts\jquery.globalize\cultures\ folder will contain many culture JavaScript files. Note, it can take five minutes to install this package.
The following code shows the modifications to the Views\Movies\Edit.cshtml file to work with the "fr-FR" culture:
@section Scripts {
   @Scripts.Render("~/bundles/jqueryval")
   <script src="~/Scripts/jquery.globalize/globalize.js"></script>
   <script src="~/Scripts/jquery.globalize/cultures/globalize.culture.fr-FR.js"></script>
   <script>
       $.validator.methods.number = function (value, element) {
          return this.optional(element) ||
              !isNaN(Globalize.parseFloat(value));
       }
       $(document).ready(function () {
          Globalize.culture('fr-FR');
       });
   </script>
   <script>
       jQuery.extend(jQuery.validator.methods, {
          range: function (value, element, param) {
             //Use the Globalization plugin to parse the value
             var val = $.global.parseFloat(value);
             return this.optional(element) || (
                 val >= param[0] && val <= param[1]);
          }
       });
   </script>
   <script>
      $.validator.methods.date = function (value, element) {
         return this.optional(element) ||
         Globalize.parseDate(value);
      }
   </script>
}
To avoid repeating this code in every Edit view, you can move it to the layout file.  To optimize the script download, see my tutorial Bundling and Minification.
As a temporary fix, if you can't get validation working in your locale, you can force your computer to use US English or you can disable JavaScript in your browser. To force your computer to use US English, you can add the globalization element to the projects root web.config file. The following code shows the globalization element with the culture set to United States English.

  <system.web>
    <globalization culture ="en-US" />
    <!--elements removed for clarity-->
  </system.web>
 Install-Package jquery-globalize

Комментариев нет:

Отправить комментарий