DataAnotation Attribute for Currency

5

I would like to format with DataAnnotation currency but default en

in the model:

[Column("cur_mensalidade")]
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:C0}")]
public decimal? Mensalidade { get; set; }

but does not accept the comma. even in web.config by placing

 <system.web>
    <globalization uiCulture="pt" culture="pt-BR" enableClientBasedCulture="false" />

Ihavetriedtocreatearegularexpression,toformat

[RegularExpression(@"^\d+(\.|\,)\d{2}$", ErrorMessage = "{0} valor incorreto.")]
    
asked by anonymous 03.05.2016 / 14:34

3 answers

1

According to the image, who is validating the input is the browser, not your app. See, and he did not create a <input type="number" /> . Well, if that's the case, the formatting is out of your control, because it depends on the browser culture, and maybe Windows.

In this case, you will have to manually create the HTML of the input field, such as <input type="text" /> and then format it in another way - javascript or backend as you like.

I've used jQuery MKoneyMask a few times. A lib jQuery made by a brazuca. Give a bizú and see if it solves your need.

    
03.05.2016 / 17:08
5

You can implement a ModelBinder for this.

public class DecimalModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext,
                                     ModelBindingContext bindingContext)
    {
        object result = null;

        // Don't do this here!
        // It might do bindingContext.ModelState.AddModelError
        // and there is no RemoveModelError!
        // 
        // result = base.BindModel(controllerContext, bindingContext);

        string modelName = bindingContext.ModelName;
        string attemptedValue =
            bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;

        // Depending on CultureInfo, the NumberDecimalSeparator can be "," or "."
        // Both "." and "," should be accepted, but aren't.
        string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
        string alternateSeperator = (wantedSeperator == "," ? "." : ",");

        if (attemptedValue.IndexOf(wantedSeperator) == -1
            && attemptedValue.IndexOf(alternateSeperator) != -1)
        {
            attemptedValue =
                attemptedValue.Replace(alternateSeperator, wantedSeperator);
        }

        try
        {
            if (bindingContext.ModelMetadata.IsNullableValueType
                && string.IsNullOrWhiteSpace(attemptedValue))
            {
                return null;
            }

            result = decimal.Parse(attemptedValue, NumberStyles.Any);
        }
        catch (FormatException e)
        {
            bindingContext.ModelState.AddModelError(modelName, e);
        }

        return result;
    }
}

And in its Global.asax in Application_Start() just add DecimalModelBinder :

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

References:

03.05.2016 / 16:54
1

This validation should be done via jquery. Create a file jquery.validade.ptBr.js

$.validator.methods.range = function (value, element, param) {
var globalizedValue = value.replace(",", ".");
return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);}$.validator.methods.number = function (value, element) { return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);}

And put it in the view. In the dataannotation, as globalization is already set to pt-br nor need to put all this information, I only leave as decimal? and it works.

But in your case, the problem is in the validation in the client nor even enter the controller. So you have to solve the javascript.

    
06.05.2016 / 13:25