ASP.NET MVC3 double validation (comma, point, null)

前端 未结 1 2024
滥情空心
滥情空心 2020-12-14 12:57

My controller looks like this:

 public class PortefeuilleController : Controller
    {
            public ActionResult Create()
            {
                        


        
相关标签:
1条回答
  • 2020-12-14 13:36

    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
    }
    
    0 讨论(0)
提交回复
热议问题