MVC3 unobtrusive jquery-val-number validation

Really struggling with jquery's built in unobtrusive validation configured by MVC3.

My object has a property:

    [DisplayName("GP")]
    [DataType(DataType.Currency)]
    [DisplayFormat(NullDisplayText = "$0", DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
    [Column("gross_profit")]
    public decimal? GrossProfit { get; set; }

      

The For editor creates a textbox which is fine however validation fails because I want users to be able to enter currency prefixes ... eg. $ 48,000 .. client side validation fails, stating that the property is not a number.

I have no problem writing my own data annotations and custom model bindings for this, but I can't figure out how to stop MVC from automatically typing this "data-val-number" into the text input simply because it is of type decimal.

I believe the "data-val-number" is stopping jquery unobtrusive validation from passing because the input field contains a dollar sign and possibly a comma.

So, I'm not looking for any advice on globalization, but rather allowing users to enter text like "$ 48,000" and check that pass ...

I would like to follow the same approach for percentages ... eg. "25%"

+3


source to share


1 answer


You don't want to use non-numeric values ​​inside the property decimal?

for display. There are several ways to handle this, but the default binder in MVC will always try to explicitly match ######. ## with a decimal field. If you have auxiliary input like $ ##, ###. ## it will blow up because it cannot be directly applied to the decimal value.

You have 2 solutions, the first is to use input masking, for example:

http://www.xaprb.com/html-input-mask/html-form-input-mask.html

or



http://digitalbush.com/projects/masked-input-plugin/

Which setting only affects the user input interface.

Or, you can use the same logic as in the model with a string data type.

[DisplayName("GP")]
[DataType(DataType.Currency)]
[DisplayFormat(NullDisplayText = "$0", DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
[Column("gross_profit")]
public string CurrencyDisplay { get; set; }

public decimal? CurrencyInput 
{
    get
    {
        //parse out non-int fields to return from value in CurrencyDisplay
    }

    set
    {
        //format string and seed into CurrencyDisplay
    }
}

      

+1


source







All Articles