asp.net mvc validation must be a number custom error

前端 未结 10 1174
时光取名叫无心
时光取名叫无心 2021-02-06 01:14

I am new to asp.net and I have a problem. When the users insert in a editor for a decimal field something other than numbers, they get an error \"Field name\" is not a number. B

10条回答
  •  后悔当初
    2021-02-06 01:37

    This is the actual answer:

    Create a class CustomClientDataTypeModelValidatorProvider. Copy the code from the MVC sources. Change the method MakeErrorString to output the appropiate message like this:

    private static string MakeErrorString(string displayName)
    {
        return string.Format(
            CultureInfo.CurrentCulture, 
            Core.Resources.Errors.EroareNuENr, 
            displayName);
    }
    

    I couldn't find a way not to copy the code just extend it as it uses this static method. If anyone knows this please tell me.

    Then, in global.asax, I wrote this:

    var cdProvider = ModelValidatorProviders.Providers.SingleOrDefault(p => p.GetType().Equals(typeof(ClientDataTypeModelValidatorProvider)));
                if(cdProvider != null)
                {
                    ModelValidatorProviders.Providers.Remove(cdProvider);
                    ModelValidatorProviders.Providers.Add(
                            new CustomClientDataTypeModelValidatorProvider());
                }
    

    so that the flow would actually be routed to my class and not the class in the asp.net MVC dll

    I got the idea from here:

提交回复
热议问题