Search code examples
asp.net-mvc-3client-side-validation

ASP.NET MVC 3 - Client-Validation with money field


I did followed this blog here and here.

And i have the following problem.

One field in my form is currecy format, from brazil. I'm using client-side validation. Everything works great expept one issue.

I have 2 validation:

[DisplayName("Taxa de adesão")]
[MoedaReal(ErrorMessage = "Taxa deve ser numérico")]        
[Required(ErrorMessage = "Taxa é obrigatório")]
public decimal ValorAdesao { get; set; }

The rule REQUIRED works ok, the MoedaReal rule works okay. After these rules are passed ok, one final rule is triggered:

  • The field Taxa de adesão must be a number

I already tried to change the web.config in this line:

<globalization culture="pt-br" uiCulture="pt-br" />

My numbers format accepcted are these:

1,00
11,00
111,00
1.111,00
11.111,00
111.111,00
1.111.111,00
1.111.111.111.111,00

How can i "fool" .NET to accept this format? Because it expects DECIMAL format instead.


Solution

  • You can't fool the default model binder. It simply tries to parse the request string value into a decimal using the culture specified in your web.config. So because you are also using client validation there might be a culture difference between the client and the server. For example the browser could be configured to use en-US and the server pt-BR and then you might have a problem. You could try this:

    <globalization culture="auto" uiCulture="auto" />
    

    This means that the culture used by the server will be dictated by the client. If this doesn't work you have a couple of other possibilities:

    • Write a custom model binder
    • Use string instead of decimal and then do the parsing manually