OK, so you have validation activated at 2 levels: server side and client side. Let's first deal with the server side validation issue.
The first thing when working with money (which is what I suppose the Saldo
field represents is to use decimals, not doubles). So the first change would be:
[DisplayName("Saldo")]
public decimal Saldo { get; set; }
OK, now let's adapt a little the Haacked model binder to your situation (accepting .
and ,
as decimal separator as well as empty values)
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (string.IsNullOrEmpty(valueResult.AttemptedValue))
{
return 0m;
}
var modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
actualValue = Convert.ToDecimal(
valueResult.AttemptedValue.Replace(",", "."),
CultureInfo.InvariantCulture
);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
which of course will be registered in Application_Start
:
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
At this stage we have solved the server side validation issue. As far as the client side validation is concerned you could use the jQuery globalization plugin that Microsoft released. Scott Hanselman has also blogged about it. So once you install it you could force the client side culture and override the $.validator.methods.number
method which is responsible for performing the client side validation:
$.validator.methods.number = function (value, element) {
// TODO: return true or false if value is a valid decimal
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…