ASP.Net MVC 2 Model Validation Regex Validator fails

前端 未结 2 1251
暗喜
暗喜 2020-12-21 16:03

I have following property in my Model Metadata class:

[Required(ErrorMessage = \"Spent On is required\")]
[RegularExpression(@\"[0-1][0-9]/[0-3][0-9]/20[12][         


        
2条回答
  •  鱼传尺愫
    2020-12-21 16:50

    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

提交回复
热议问题