Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show support jQuery validation for non-English locales that use a comma (",") for a decimal point #4076

Open
Rick-Anderson opened this issue Aug 23, 2017 · 72 comments

Comments

@Rick-Anderson
Copy link
Contributor

Rick-Anderson commented Aug 23, 2017

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation mentions
You may not be able to enter decimal points or commas in the Price field. To support jQuery validation for non-English locales that use a comma (",") for a decimal point, and non US-English date formats, you must take steps to globalize your app.

Need tutorial that shows how to do this. Until the tutorial is written, follow these instructions:

On Index.cshtml add

@System.Globalization.CultureInfo.CurrentUICulture

Refreshing the page you should see en-US displayed at the very top.
This will help to see if you does have localization enabled on mvc. When localization is working it can be removed.

To enable another locale than default on mvc you need to add localization support (read Globalization and localization in ASP.NET Core)

For this sample, let's just add es-UY locale and set as the default.

on Startup.cs:

app.UseRequestLocalization("en-UY", "fr-FR");

this will add support for locale "es-UY" and also make it the default culture.

refreshing the Index page on your browser should now show es-UY as the current UI locale.

At this point, using decimal points on the client as 19.50 will allow the jQuery validation but on the server it won't be seen as decimals so you will end with 1.950,00 value.

Then you need to use Globalize with jquery-validation-globalize plugin.

See Globalize installation instructions and jquery-validation-globalize installation instructions. Unfortunately those instructions use bower for the installation and the ASP.NET CORE 2.0 and late doesn't use bower. If you want to use the recommended NPM way, you can still do it. Either way, I highly recommend you check out both projects for documentation and more info. You just need to install Globalize with jquery-validation-globalize plugin - how you do it is secondary.

After you managed to install Globalize and jquery-validation-globalize plugin then you need to use it on your html pages.

on _ValidationScriptsPartial.cshtml add the new required javascript files (after jQuery):

<!-- cldr scripts (needed for globalize) -->
<script src="~/lib/cldrjs/dist/cldr.js"></script>
<script src="~/lib/cldrjs/dist/cldr/event.js"></script>
<script src="~/lib/cldrjs/dist/cldr/supplemental.js"></script>

<!-- globalize scripts -->
<script src="~/lib/globalize/dist/globalize.js"></script>
<script src="~/lib/globalize/dist/globalize/number.js"></script>
<script src="~/lib/globalize/dist/globalize/date.js"></script>

<script src="~/lib/jquery-validation-globalize/jquery.validate.globalize.js"></script>

Refresh your page, it should work with the current culture (in this case, es-UY).

The LibMan tool requires VS 15.8.0 Preview 2.0 or later.

Hope it helps.
image

@Rick-Anderson Rick-Anderson added Pri1 High priority, do before Pri2 and Pri3 topic Help wanted Up for grabs. We would accept a PR to help resolve this issue labels Aug 23, 2017
@Rick-Anderson Rick-Anderson added this to the Backlog milestone Aug 23, 2017
@Rick-Anderson
Copy link
Contributor Author

@damienbod @Bartmax @hishamco would one of you be able to help out with this? (or recommend someone)?

@Rick-Anderson
Copy link
Contributor Author

@ryanbrandenburg @danroth27 this is a frequent complaint of customers. Can I get some help on showing how to do this?

@Bartmax
Copy link

Bartmax commented Sep 1, 2017

@Rick-Anderson

On Index.cshtml add

@System.Globalization.CultureInfo.CurrentUICulture

Refreshing the page you should see en-US displayed at the very top.
This will help to see if you does have localization enabled on mvc. When localization is working it can be removed.

To enable another locale than default on mvc you need to add localization support (read Globalization and localization in ASP.NET Core)

For this sample, let's just add es-UY locale and set as the default.

on Startup.cs:

var defaultCulture = new CultureInfo("es-UY");
var localizationOptions = new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture(defaultCulture),
    SupportedCultures = new List<CultureInfo> { defaultCulture },
    SupportedUICultures = new List<CultureInfo> { defaultCulture }
};
app.UseRequestLocalization(localizationOptions);

this will add support for locale "es-UY" and also make it the default culture.

refreshing the Index page on your browser should now show es-UY as the current UI locale.

At this point, using decimal points on the client as 19.50 will allow the jQuery validation but on the server it won't be seen as decimals so you will end with 1.950,00 value.

Then you need to use Globalize with jquery-validation-globalize plugin.

You can find here Globalize installation instructions and jquery-validation-globalize installation instructions. Unfortunately those are for bower and the ASP.NET CORE team moved away (a good thing) from bower so if you want to use the recommended NPM way, you can still do it. Either way, I highly recommend you check out both projects for documentation and more info.

After you managed to install Globalize and jquery-validation-globalize plugin then you need to use it on your html pages.

on _ValidationScriptsPartial.cshtml add the new required javascript files (after jQuery):

<!-- cldr scripts (needed for globalize) -->
<script src="~/lib/cldrjs/dist/cldr.js"></script>
<script src="~/lib/cldrjs/dist/cldr/event.js"></script>
<script src="~/lib/cldrjs/dist/cldr/supplemental.js"></script>

<!-- globalize scripts -->
<script src="~/lib/globalize/dist/globalize.js"></script>
<script src="~/lib/globalize/dist/globalize/number.js"></script>
<script src="~/lib/globalize/dist/globalize/date.js"></script>

<script src="~/lib/jquery-validation-globalize/jquery.validate.globalize.js"></script>

Refresh your page, it should work with the current culture (in this case, es-UY).

Hope it helps.
image

[Edit, moved from top to here]Some notes:

The RegularExpression attribute is used to limit what characters can be input. In the code above, Genre and Rating must use only letters (white space, numbers and special characters are not allowed).

The regular expression is not doing what's described, more notably it requires first letter to be Uppercase.

@Bartmax
Copy link

Bartmax commented Sep 1, 2017

and don't think you need it, but just in case I made the sample project available on my github at https://github.com/Bartmax/MvcMovie.LocalizationSample (let me know when I can delete it)

@Rick-Anderson
Copy link
Contributor Author

Thanks @Bartmax

@kadariuk
Copy link

@Bartmax I have this error in js, during validation, not you?

jquery.validate.js:666 Uncaught Error: E_DEFAULT_LOCALE_NOT_DEFINED: Default locale has not been defined.
at createError (globalize.js:105)
at validate (globalize.js:182)
at validateDefaultLocale (globalize.js:213)
at Function.Globalize.numberParser.Globalize.numberParser (number.js:1422)
at Function.Globalize.parseNumber.Globalize.parseNumber (number.js:1474)
at $.validator.methods.number (jquery.validate.globalize.js:21)
at $.validator.check (jquery.validate.js:639)
at $.validator.element (jquery.validate.js:437)
at $.validator.onfocusout (jquery.validate.js:266)
at HTMLInputElement.delegate (jquery.validate.js:380)
createError @ globalize.js:105
validate @ globalize.js:182
validateDefaultLocale @ globalize.js:213
Globalize.numberParser.Globalize.numberParser @ number.js:1422
Globalize.parseNumber.Globalize.parseNumber @ number.js:1474
$.validator.methods.number @ jquery.validate.globalize.js:21
check @ jquery.validate.js:639
element @ jquery.validate.js:437
onfocusout @ jquery.validate.js:266
delegate @ jquery.validate.js:380
dispatch @ jquery.js:4732
elemData.handle @ jquery.js:4544
trigger @ jquery.js:7788
simulate @ jquery.js:7859
handler @ jquery.js:7922

@coykto-repos
Copy link

coykto-repos commented Sep 20, 2017

I would really like to let both comma and dot to be accepted as a decimal separator. In Russia and i guess in some other places it is ok to use either dot or comma to separate decimal values, but for the thousands people tend to use spaces, like that: 125 000 000.25

Also, i just cloned repository that @Bartmax provided, it does accept comma as a separator so when i input "1,99" i get "$ 1,99", but when i type in "1.99" i get the movie with the price of "$ 199,00". It doesn't seem like an appropriate behavior.

@Calkines
Copy link

@coykto-repos is not the case of configure the model with attribute that indicate it is a currency data type? On the other hand, perhaps, you may be using a culture that needs a comma to decimal separator.

@coykto-repos
Copy link

@Calkines maybe i'm missing something as i'm not familiar with asp.net core, or .net in general for that matter. I originaly came here because i got really confused by "getting started" tutorial, writen by @Rick-Anderson and others, as neither "." nor "," passed validation for a price field. I have a Django background and i never had problems like that as the framework seems to handled these things well, but here it seems messing with jQuery validation probably would not be enough. As i mentioned, typing in values "1.99" and "1,99" should give me the same result - "$ 1.99" regardless of what culture my browser says it uses, definately not "$ 199". So, this is also server-side (or asp.net-side) problem as far as i understand it, since one of the solutions i found is to write custom IModelBinder (which is far from "getting started").

@Rick-Anderson
Copy link
Contributor Author

#4382 adds link to this issue until I have time to add this info to the doc.

@Rick-Anderson Rick-Anderson self-assigned this Sep 25, 2017
@bcalcas
Copy link

bcalcas commented Nov 29, 2017

This happened after I updated the file .bowercc file:

bower ECMDERR Failed to execute "node ./node_modules/cldr-data-downloader/bin/download.js -i bower_components/cldr-data/index.json -o bower_components/cldr-data/", exit code of #1
Whops ENOENT: no such file or directory, open 'C:\Users\Utilizador\source\repos\MyProject\MyProject\bower_components\cldr-data\index.json'

Additional error details:
Whops ENOENT: no such file or directory, open 'C:\Users\Utilizador\source\repos\MyProject\MyProject\bower_components\cldr-data\index.json'

@JoaoVictorCardoso
Copy link

please say where I can found this file ".bowercc"
I just fund "bower.json" files inside wwwrot>lib>...(multiple folders)

@Peter578
Copy link

I found 16 bower.json files in my Project but no .bowercc. After installing jquery-validation-globalize there is a new hidden dir 'bower_components' where i find cldrjs, jquery-validation-globalize and some others.
What should i reference in 'ValidationScriptsPartial.cshtml' ? Move the Contents to www.lib?
I am using Visual Studio 2017 ver 15.15.2 on a german language System.
Displaying Date works fine but in .net core 2.0 the fields always display american date-format giving Errors on german date Format (dd.mm.yyyy).

@bcalcas
Copy link

bcalcas commented Jan 15, 2018

@JoaoVictorCardoso bower.cc is "inside" bower.json
img

@Peter578
Copy link

Sorry, no bower.json in my project root. I just created two new Project (ASP.NET Core-Webanwendung / MVC / Core 2.0). Added jquery-validation-globalize thru Nuget in one Project, thru bower in the other.
Bower installer said: "no-json No bower.json file to save to, use bower init to create one".
Now i'll Google for "bower init"...

@bcalcas
Copy link

bcalcas commented Jan 15, 2018

@Peter578 bower is about to be discontinued in asp.netcore 2.0. Maybe because of that you can't see the bower.cc file in your project.
Check this link: https://wildermuth.com/2017/11/19/ASP-NET-Core-2-0-and-the-End-of-Bower

This thread was to support .net core 1.x (I think)

@Rick-Anderson
Copy link
Contributor Author

@Bartmax

IMPORTANT: First update .bowercc to looks like this:

Can you update this?

@Bartmax
Copy link

Bartmax commented Jan 24, 2018

@Rick-Anderson update how?

@Rick-Anderson
Copy link
Contributor Author

@Bartmax I'm getting lots of comments - now that we don't use bower this doesn't work.

@Bartmax
Copy link

Bartmax commented Jan 25, 2018

@Rick-Anderson the authors of both plugins document bower as the "package manager way" to get the libraries. I updated the issue but I think it's out of the scope how to get js libraries from whichever is the package manager of the day.

Let me know if the current update works for you.

@XelaNimed
Copy link

XelaNimed commented Feb 16, 2018

Hello!
Thanks to @Bartmax but answer not resolved problem, because JavaScript error in console occurred: E_DEFAULT_LOCALE_NOT_DEFINED (have @MatteoSevera too).
I solved this problem so:

  1. First, you need to modify the file .bowerrc (you can find it under the file bower.json):
{
  "directory": "wwwroot/lib",
  "scripts": {
    "preinstall": "npm install cldr-data-downloader@0.2.x",
    "postinstall": "node ./node_modules/cldr-data-downloader/bin/download.js -i wwwroot/lib/cldr-data/index.json -o wwwroot/lib/cldr-data/"
  }
}
  1. Check dependecies in bower.json:
{
  "name": "asp.net",
  "private": true,
  "dependencies": {
    "bootstrap": "3.3.7",
    "jquery": "3.2.1",
    "jquery-validation": "1.17.0",
    "jquery-validation-unobtrusive": "3.2.6",
    "cldr-data": "29.0.0",
    "globalize": "v0.1.1",
    "jquery-validation-globalize": "1.0.0",
    "cldrjs": "0.5.0"
  },
  "resolutions": {
    "globalize": "^1.0.0",
    "jquery": "3.2.1",
    "cldrjs": "0.5.0",
    "jquery-validation": "1.17.0"
  }
}
  1. Modify file _ValidationScriptsPartial.cshtml like so:
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>

<!-- cldr scripts (needed for globalize) -->
<script src="~/lib/cldrjs/dist/cldr.js"></script>
<script src="~/lib/cldrjs/dist/cldr/event.js"></script>
<script src="~/lib/cldrjs/dist/cldr/supplemental.js"></script>

<!-- globalize scripts -->
<script src="~/lib/globalize/dist/globalize.js"></script>
<script src="~/lib/globalize/dist/globalize/number.js"></script>
<script src="~/lib/globalize/dist/globalize/date.js"></script>

<script src="~/lib/jquery-validation-globalize/jquery.validate.globalize.js"></script>

@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment HostingEnvironment
@{
    string GetDefaultLocale() {
        const string localePattern = "lib\\cldr-data\\main\\{0}";
        var currentCulture = System.Globalization.CultureInfo.CurrentCulture;
        var cultureToUse = "ru-RU"; //Default regionalisation to use

        if (System.IO.Directory.Exists(System.IO.Path.Combine(HostingEnvironment.WebRootPath, string.Format(localePattern, currentCulture.Name))))
            cultureToUse = currentCulture.Name;
        else if (System.IO.Directory.Exists(System.IO.Path.Combine(HostingEnvironment.WebRootPath, string.Format(localePattern, currentCulture.TwoLetterISOLanguageName))))
            cultureToUse = currentCulture.TwoLetterISOLanguageName;

        return cultureToUse;
    }
}

<script type="text/javascript">
    var culture = "@GetDefaultLocale()";
    $.when(
        $.get("/lib/cldr-data/supplemental/likelySubtags.json"),
        $.get("/lib/cldr-data/main/" + culture + "/numbers.json"),
        $.get("/lib/cldr-data/supplemental/numberingSystems.json"),
        $.get("/lib/cldr-data/main/" + culture + "/ca-gregorian.json"),
        $.get("/lib/cldr-data/main/" + culture +"/timeZoneNames.json"),
        $.get("/lib/cldr-data/supplemental/timeData.json"),
        $.get("/lib/cldr-data/supplemental/weekData.json")
    ).then(function () {
        // Normalize $.get results, we only need the JSON, not the request statuses.
        return [].slice.apply(arguments, [0]).map(function (result) {
            return result[0];
        });
    }).then(Globalize.load).then(function () {
        Globalize.locale(culture);
    });
</script>

This solution from article by Stefan Vincent Haug.

Why does the official documentation refer to an answer that does not solve the problem?

@Rick-Anderson
Copy link
Contributor Author

@Bartmax I copied your instructions to the top of the issue to resolve some problems people had with the comment we don't use bower. I also fixed a couple problems you mentioned with the tutorial (changes will show up in a couple days) and removed those comments. Can you review my edits? Is there anything we could do to make the instructions easier to follow?

@Rick-Anderson Rick-Anderson changed the title Show support jQuery validation for non-English locales that use a comma (",") for a decimal poin Show support jQuery validation for non-English locales that use a comma (",") for a decimal point Jan 7, 2021
@rogeriokoski
Copy link

Just an update on the nice solution provided by @XelaNimed as the newly versions of Visual Studio do not use Bower anymore and cldr-data changed to cldr-json.
Notice the paths for the json changed as well as the path in localePattern variable:

@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment
@{
    string GetDefaultLocale()
    {
        const string localePattern = "lib\\cldr-json\\cldr-numbers-modern\\main\\{0}";
        var currentCulture = System.Globalization.CultureInfo.CurrentCulture;
        var cultureToUse = "en-US"; //Default regionalisation to use

        if (System.IO.Directory.Exists(System.IO.Path.Combine(HostingEnvironment.WebRootPath, string.Format(localePattern, currentCulture.Name))))
            cultureToUse = currentCulture.Name;
        else if (System.IO.Directory.Exists(System.IO.Path.Combine(HostingEnvironment.WebRootPath, string.Format(localePattern, currentCulture.TwoLetterISOLanguageName))))
            cultureToUse = currentCulture.TwoLetterISOLanguageName;

        return cultureToUse;
    }
}
<script type="text/javascript">
    var culture = "@GetDefaultLocale()";
    $.when(
        $.get("/lib/cldr-json/cldr-core/supplemental/likelySubtags.json"),
        $.get("/lib/cldr-json/cldr-numbers-modern/main/" + culture + "/numbers.json"),
        $.get("/lib/cldr-json/cldr-core/supplemental/numberingSystems.json"),
        $.get("/lib/cldr-json/cldr-dates-modern/main/" + culture + "/ca-gregorian.json"),
        $.get("/lib/cldr-json/cldr-dates-modern/main/" + culture +"/timeZoneNames.json"),
        $.get("/lib/cldr-json/cldr-core/supplemental/timeData.json"),
        $.get("/lib/cldr-json/cldr-core/supplemental/weekData.json")
    ).then(function () {
        // Normalize $.get results, we only need the JSON, not the request statuses.
        return [].slice.apply(arguments, [0]).map(function (result) {
            return result[0];
        });
    }).then(Globalize.load).then(function () {
        Globalize.locale(culture);
    });
</script>

@Lesnoj84
Copy link

Lesnoj84 commented Apr 9, 2022

This must be a tutorial for beginners, but steps that are written here are more than complicated. I have not a single idea what you need to do.
It was clear until author starts to throw all kind of other links at and saying that you need to do this and that click here and there and bla bla bla. Really this isnt much of a help.

@ffslight
Copy link

The steps to get globalization to work as suggested here, does not seem to work in Visual Studio 2022.

@rafaelrpd
Copy link

rafaelrpd commented Jun 12, 2022

Hey guys, how are you all?

If you're getting hard time to solve this globalize install problem, there is how I've solved it to follow properly Razor Pages tutorial.

  1. You need to learn how to use libman, it will help you a lot. Use LibMan with ASP.NET Core in Visual Studio

  2. At solution explorer, add Client-Side Library and install those libraries:

    • From CDNJS provider:
      • globalize

        put it inside wwwroot/lib/globalize/

      • cldrjs

        put it inside wwwroot/lib/cldrjs/

    • From JSDELIVR:
      • jquery-validation-globalize

        put it inside wwwroot/lib/jquery-validation-globalize/

  3. With those libs properly installed, you need to add this lines of code at bottom of /Pages/Shared/__ValidationScriptsPartial.cshtml

<!-- cldr script (needed for globalize) -->
<script src="~/lib/cldrjs/cldr.js"></script>
<!-- globalize script -->
<script src="~/lib/globalize/globalize.js"></script>
<!-- jquery validation script with globalize -->
<script src="~/lib/jquery-validation-globalize/jquery.validate.globalize.js"></script>
  1. If you're following the razor pages tutorial all along, you should EDIT, all apps put this line of code inside Program.cs. Remember to put it before app.Run();
app.UseRequestLocalization("YOUR_LOCALIZATION");

Change YOUR_LOCALIZATION to your real localization, like taught by @Rick-Anderson at first answer. 👉 First answer

Btw, thank you Rick-Anderson! Much appreciated your help at this matter, it was driving me crazy.

@eduarddejong
Copy link

eduarddejong commented Jun 21, 2022

Hi,
I am coming from the ASP.NET Razor Pages tutorial as well, te be more precies:
https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/validation?view=aspnetcore-6.0&tabs=visual-studio

Even as an experienced developer in many technologies (but not so much modern ASP.NET Core yet - that's why I wanted to follow this tutorial), I experience some issues.

First we have the point that the docs are really a bit messy (for example: things of general relevance only being visible under the "Visual Studio Code" tab) and also really a bit outdated (for example: Part 2 talks about many problems and warnings with null check errors which are all solved issues in the current version).

But let's talk about the specific issue with Globalization/Localization here, because I am trying to get things working as well.
I notice issues on multiple aspects:

  1. The first thing someone sees when navigating with the links to this page is someone talking about "Startup.cs". This is not part of the default template in .NET 6 anymore, but refers to older ASP.NET Core projects. Which confuses new people.

  2. A bit of trying with available methods in VS Code reveals to me multiple ways of configuring Localization:

  • builder.Services.AddLocalization()
  • builder.Services.AddRequestLocalization(options => { /* Certain configuration here. */ })
  • app.UseRequestLocalization(), which also has a parameterless version (can we use that and wat does it do?)
    etc.
    I miss clarity here. Nobody else seems to talk about the first two from the IServiceCollection that I mentioned here, but maybe we can use those as well or maybe we even need those.

@j03ll0b0
Copy link

j03ll0b0 commented Oct 9, 2022

Hey guys, how are you all?

If you're getting hard time to solve this globalize install problem, there is how I've solved it to follow properly Razor Pages tutorial.

  1. You need to learn how to use libman, it will help you a lot. Use LibMan with ASP.NET Core in Visual Studio

  2. At solution explorer, add Client-Side Library and install those libraries:

    • From CDNJS provider:

      • globalize

        put it inside wwwroot/lib/globalize/

      • cldrjs

        put it inside wwwroot/lib/cldrjs/

    • From JSDELIVR:

      • jquery-validation-globalize

        put it inside wwwroot/lib/jquery-validation-globalize/

  3. With those libs properly installed, you need to add this lines of code at bottom of /Pages/Shared/__ValidationScriptsPartial.cshtml

<!-- cldr script (needed for globalize) -->
<script src="~/lib/cldrjs/cldr.js"></script>
<!-- globalize script -->
<script src="~/lib/globalize/globalize.js"></script>
<!-- jquery validation script with globalize -->
<script src="~/lib/jquery-validation-globalize/jquery.validate.globalize.js"></script>
  1. If you're following the razor pages tutorial all along, you should put this line of code inside Program.cs. Remember to put it before app.Run();
app.UseRequestLocalization("YOUR_LOCALIZATION");

Change YOUR_LOCALIZATION to your real localization, like taught by @Rick-Anderson at first answer. point_right First answer

Btw, thank you Rick-Anderson! Much appreciated your help at this matter, it was driving me crazy.

my VS Code About page:
Versión: 1.72.0
Commit: 64bbfbf67ada9953918d72e1df2f4d8e537d340e
Fecha: 2022-10-04T23:20:47.539Z
Electrón: 19.0.17
Chromium: 102.0.5005.167
Node.js: 16.14.2
V8: 10.2.154.15-electron.0
OS: Linux x64 5.19.14-xanmod1
En espacio aislado: No
I can confirm this solution works just fine, es-VE

dotnet tool install -g Microsoft.Web.LibraryManager.Cli
libman init
libman install globalize
libman install cldrjs
libman install jquery-validation-globalize --provider jsdelivr

then following the rest as described by @rafaelrpd at Here

@dannevesdantas
Copy link
Contributor

dannevesdantas commented Nov 27, 2022

@Rick-Anderson does it make sense to write the instructions provided here by @rafaelrpd in the body of the https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation page?

@Rick-Anderson
Copy link
Contributor Author

Rick-Anderson commented Nov 28, 2022

@damienbod @Bartmax @hishamco would one of you be able to review the instructions provided here by @rafaelrpd

@Rick-Anderson Rick-Anderson added RR Rick-Anderson needs to review this periodically re-Artak @mkArtakMSFT must review labels Nov 28, 2022
@Rick-Anderson
Copy link
Contributor Author

@mkArtakMSFT can you have someone review the instructions provided here by @rafaelrpd

@Rick-Anderson Rick-Anderson added the Top10 Top 10 issue to review label Nov 28, 2022
@hishamco
Copy link
Member

<script src="~/lib/globalize/globalize.js"></script>

@rafaelrpd @Rick-Anderson could you please let me know what this script is doing? This is the first time I see it

BTW this is one of the oldest issues in localizations, it mainly related to jQuery if I'm not wrong

@damienbod
Copy link
Contributor

LGTM maybe an integrity check is needed if including the js file from a CDN

@dannevesdantas
Copy link
Contributor

I remember the instructions provided by @rafaelrpd for using globalize.js is quite similar to the instructions in the old Getting Started with ASP.NET MVC 4/5 pages at here and here from 2013/2014. The globalize.js GitHub project's page is https://github.com/globalizejs/globalize and it’s also available from npm and bower. It’s a very popular project on GitHub btw.

@dannevesdantas
Copy link
Contributor

Looks like it’s also possible to adapt and update the text and instructions provided in the old "Getting Started with ASP.NET MVC 4/5" tutorials from here and here to the current .NET version, with no major changes.

@hishamco
Copy link
Member

We need to check ..

@dannevesdantas
Copy link
Contributor

@Rick-Anderson @hishamco it also solves #8585

@hishamco
Copy link
Member

Franlky I didn't try before, also never heard about it :)

@Rick-Anderson again I see the issue related to jQuery, the question is what's the issue from localization APIs?

@Rick-Anderson Rick-Anderson removed Top10 Top 10 issue to review RR Rick-Anderson needs to review this periodically re-Artak @mkArtakMSFT must review labels Nov 28, 2022
@garbiru
Copy link

garbiru commented Dec 11, 2022

The solution from @rafaelrpd works fine, but the problem is, it only works for server-side validations, the client-side stopped working.

Is there any solution to this?

@Skleni
Copy link

Skleni commented Jan 30, 2023

The solution from @rafaelrpd works fine, but the problem is, it only works for server-side validations, the client-side stopped working.

Is there any solution to this?

@garbiru Did you find a solution?

@fomoshlo3
Copy link

fomoshlo3 commented Apr 16, 2023

I may have read over it. But what's the solution now?

And where i can find better tutorials for asp.net than on learn.microsoft?
I mean i see you try to solve this and have propably put much work into it, but this isn't the first 'Tutorial' from learn.microsoft that feels like loss-of-time due to inconsequent documentation and confusion by mentioning solutions for older versions of that whole framework thinggy.

@onetoucheddy
Copy link

Folowing code worked in VS 2017 ASP.NET application Framework 4.5

using Microsoft.AspNet.Localization;
using System.Web.Mvc;

public partial class Startup
{
    public class LanguageActionFilter : ActionFilterAttribute
    {
        private readonly ILogger _logger;

        public LanguageActionFilter(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger("LanguageActionFilter");
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string culture = context.RouteData.Values["culture"].ToString();
            _logger.LogInformation($"Setting the culture from the URL: {culture}");

#if NET451
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
#elif NET46
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
#else
// CultureInfo.CurrentCulture = new CultureInfo(culture);
// CultureInfo.CurrentUICulture = new CultureInfo(culture);
#endif
base.OnActionExecuting(context);
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.AddScoped<LanguageActionFilter>();

        services.Configure<RequestLocalizationOptions>(
            options =>
            {
                var supportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("en-US"),
                        new CultureInfo("de-CH"),
                        new CultureInfo("fr-CH"),
                        new CultureInfo("it-CH"),
                        new CultureInfo("nl"),
                        new CultureInfo("en-AU"),
                        new CultureInfo("en-GB"),
                        new CultureInfo("en"),
                        new CultureInfo("es-ES"),
                        new CultureInfo("es-MX"),
                        new CultureInfo("es"),
                        new CultureInfo("fr-FR"),
                        new CultureInfo("fr-BE")
                                    };

                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
            });
    }

How to make this work in ASP.NET core 7.0 in VS 2022?
The docs and implementations I found so far are not working or incomplete.
After 40 years of programming, there is still no easy way to implement a decimal comma instead of a point? I must be missing something.

@christian0712
Copy link

TUVE EL MISMO PROBLEMA Y LO SOLUCIONE EN 2 PASOS! Gracias a ChatGPT

  1. Solo agregas en wwroot/js/validation.js (este archivo y dentro escribes)
    $.validator.methods.number = function (value, element) {
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:.\d{3})+)(?:,\d+)?$/.test(value);
    };

  2. Cargas este archivo en Pages/Shared/_ValidationScriptsPartial.cshtml

<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script> <script src="/js/validation.js"></script>

Y listo funcionando! al 100% pones volver a cargar el proyecto f5 y puedes poner decimales ejemplo: 5,60

@onetoucheddy
Copy link

onetoucheddy commented Aug 8, 2023 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests