ASP.Net MVC 2 Model Validation Regex Validator fails

馋奶兔 提交于 2019-11-29 15:37:39
Darin Dimitrov

That's because regex applies to strings and not DateTime properties. If the user enters an invalid string which cannot be parsed to a DateTime instance from the model binder it will add a generic error message before your regex pattern executes.

You have a couple of possibilities:

  1. Customize the error message in a resource file
  2. Write a custom model binder
  3. Use a string property (I feel guilty for proposing this :-))
cleftheris

Actualy there is another workaround for this. You can simply subclass the RegularExpressionAttribute

public class DateFormatValidatorAttribute : RegularExpressionAttribute {
    public DateFormatValidatorAttribute()
        : base(@"[0-1][0-9]/[0-3][0-9]/20[12][0-9]") 
        {
            ErrorMessage = "Please enter date in mm/dd/yyyy format";
        }

        public override bool IsValid(object value) {
            return true;
        }
}

in your Global.asax.cs on application start register the RegularExpression addapter for client side validation like so:

DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(DateFormatValidatorAttribute), 
                typeof(RegularExpressionAttributeAdapter));

Now you get to have the build-in MVC regular exression validator client side and keep the DateTime as your property type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!