Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate a currency field?

I have an ASP.NET MVC-4 application with this currency field:

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}", ConvertEmptyStringToNull = true)]
    [DataType(DataType.Currency)]
    public decimal? Price { get; set; }

This is the corresponding part in my view:

    @Html.EditorFor(model => model.Price)
    @Html.ValidationMessageFor(model => model.Price)

If the price is 100 Euro the text field in the view shows:

100,00 €

This is nice.

But I am having problems as soon as I try to do a Postback. The validator pops up and says that the price field needs to be a number.

I can only fix this if (1) I delete the € symbol and (2) replace the decimal separator (replace comma with a dot).

If there is no better solution, I guess I could change the DataFormatString = "{0:F2}" in order to avoid the currency symbol.

But how do I make the validator accept the comma as decimal separator instead of the (American) dot?

Thanks for your help, guys!

like image 519
Ingmar Avatar asked Nov 13 '22 01:11

Ingmar


1 Answers

So, I was able to solve my problem with jQuery's Globalization plugin from http://github.com/jquery/globalize.

I added the following files to my /scripts folder:

  • /scripts/globalize.js
  • /scripts/cultures/globalize.cultures.js
  • /sctipts/cultures/globalize.culture.de-DE.js

In BundleConfig.cs:

bundles.Add(new ScriptBundle("~/bundles/scripts/globalization").Include(
          "~/Scripts/globalize*",
          "~/Scripts/cultures/globalize*"));

In _Layout.cshtml:

@Scripts.Render("~/bundles/scripts/globalization")

and in the script section of _Layout.cshtml:

$.validator.methods.number = function (value, element) {
            return this.optional(element) || !isNaN(Globalize.parseFloat(value));
        }
        $.validator.methods.range = function (value, element, param) {
            return this.optional(element) || (Globalize.parseFloat(value) >= param[0] && Globalize.parseFloat(value) <= param[1]);
        }

However, I couldn't make the currency symbol to work with the client validation, so I also changed the data annotation as follows:

[DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:c}", ConvertEmptyStringToNull = true)]

But that was it. No other changes necessary. I can now enter values like "1,49" or "18,77" and everything gets stored properly in my database.

like image 87
Ingmar Avatar answered Nov 15 '22 12:11

Ingmar