Pergunta

I have a MVC4 application with unobstrusive javascript client-side validation. This is working fine except for decimal validation. I am encoutering some strange and annoying behaviour.

The decimal validation only allows numbers with three numbers after the decimal separator. However i want this to work with two numbers after the separator (or just any number is fine as it should do by default if i'm correct).

so 1.222 is valid and 1.22 and isn't while i wan't it to be valid. (1.2222 is neither valid).

in my view i have a normal:

@Html.TextBoxFor(x => x.BasePrice)

my model:

[Required]
public decimal BasePrice { get; set; }

and my controller:

ProductVM model = new ProductVM()
{
    BasePrice = product.BasePrice
};
  • product is an Entity Framework 4 entityobject

I've also tried putting;

[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]

in my model. But this doesn't work either. It has no effect.

I've never seen any behaviour like this when working with MVC. I have no idea where to look. Any clues?

Foi útil?

Solução

I still don't know what the problem is, but I fixed it with a little bit dirty workaround:

$.validator.methods.number = function (value, element) {

    if(!isNaN(parseFloat(strValue)))
    {
        return true;
    }   

    return false;

}

by overriding the client side decimal validation. just added this in a script block in my _layout.cshtml.

server side validation will ensure the security is still ok by complete validation.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top