I need to implement a currency input where the property type needs to be decimal or double and accept the format "0.00,00".
ViewModel
[RegularExpression(@"^([1-9]{1}[\d]{0,2}(\.[\d]{3})*(\,[\d]{0,2})?|[1-9]{1}[\d]{0,}(\,[\d]{0,2})?|0(\,[\d]{0,2})?|(\,[\d]{1,2})?)$")]
public Decimal Salario { get; set; }
EditorTemplate
@model Decimal?
@Html.TextBox("", Model.HasValue && Model.Value > 0 ? Model.Value.ToString() : "", new { @class = "form-control text-box single-line money" })
<script type="text/javascript">
$(document).ready(function () {
$(".money").maskMoney({ thousands: '.', decimal: ',', prefix: "" });
});
</script>
I also have set on my web.config culture="pt-BR". The problem is that the input is only accepting values like "123,98", if i type "1.123,98" I get the error message "The value '9.999,99' is not valid for Salario.". Is there a way to make it allows the dots and comma? I don't want to use System.String.
UPDATE - The solution
I finally found a solution! This is my final code:
EditorTemplate
@model Double?
@Html.TextBox("", Model.HasValue && Model.Value > 0 ? Model.Value.ToString() : "", new { @class = "form-control text-box single-line money" })
<script type="text/javascript">
$(document).ready(function () {
$(".money").maskMoney({ thousands: '.', decimal: ',', prefix: "R$ " });
});
</script>
ViewModel
[DataType("Money")] //Money is the name of my EditorTemplate
public decimal Valor { get; set; }
Custom Model Binder
public class DoubleModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return valueProviderResult != null && !string.IsNullOrEmpty(valueProviderResult.AttemptedValue) ? Convert.ToDouble(valueProviderResult.AttemptedValue.Replace("R$", "").Trim()) : base.BindModel(controllerContext, bindingContext);
}
}
Global.asax
ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
ModelBinders.Binders.Add(typeof(double?), new DoubleModelBinder());
This custom model binder is used to format the value before it is sent to controller. I found the solution on this post: Accept comma and dot as decimal separator.
Thanks!