Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure culture for client side validation in ASP.NET Core MVC

I having very hard time to configure client side validation in my APP. I would like to it be able to accept localized pt-BR inputs.

I tried configure the app using at startup:

var locale = "pt-BR";
RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions {
    SupportedCultures   = new List<CultureInfo> { new CultureInfo(locale) },
    SupportedUICultures = new List<CultureInfo> { new CultureInfo(locale) },
    DefaultRequestCulture = new RequestCulture(locale)
};

and I set <html lang="pt-br"> into the main HTML file.

It works for rendering currency, date time and numbers in server side, but the client validation still expecting en-US input.

The client side is using jquery.validate and jquery.validate.unobtrusive

How can I configure the client side validation to understand localized input ?

like image 506
Daniel Santos Avatar asked Dec 05 '25 19:12

Daniel Santos


1 Answers

Create a helper class like this:

public class PortugueseCulture : CultureInfo
{
    private readonly Calendar cal;
    private readonly Calendar[] optionals;

    public PortugueseCulture()
        : this("pt-BR", true)
    {
    }

    public PortugueseCulture(string cultureName, bool useUserOverride) : base(cultureName, useUserOverride)
    {
        //Your Custom Currency Numbers Calendar Culture Code
    }

    public override Calendar Calendar
    {
        get { return cal; }
    }

    public override Calendar[] OptionalCalendars
    {
        get { return optionals; }
    }
}

Then in Global.asax.cs add this method

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var portugueseCulture = new PortugueseCulture();
        Thread.CurrentThread.CurrentCulture = portugueseCulture;
        Thread.CurrentThread.CurrentUICulture = portugueseCulture;
    }
like image 102
Jahed Kabiri Avatar answered Dec 07 '25 14:12

Jahed Kabiri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!