ASP.Net MVC 2 Validation Valid Regex Validator not working

I have the following property in my Model metadata class:

[Required(ErrorMessage = "Spent On is required")] [RegularExpression(@"[0-1][0-9]/[0-3][0-9]/20[12][0-9]", ErrorMessage = "Please enter date in mm/dd/yyyy format")] [DataType(DataType.Date)] [DisplayName("Spent On")] public DateTime SpentOn { get; set; } 

But whenever I call ModelState.IsValid , it always returns false, because the regular expression is not checked. I matched the entered date (08/29/2010) with the new regex using the same pattern and it fits perfectly.

What am I doing wrong?

+2
source share
2 answers

This is because the regex is applied to strings, not to DateTime properties. If the user enters an invalid string that cannot be parsed by the DateTime instance from the model binder, it will add a generic error message before your regular expression pattern is executed.

You have several options:

  • Set error message in resource file
  • Record Custom Binder
  • Use the string property (I feel guilty for the suggestion :-))
+1
source

In fact, there is another workaround for this. You can just subclass 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 application, when starting the application, register the RegularExpression add-on for client-side validation as follows:

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

Now you have the built-in client side of excity MVC authentication and keep the DateTime as the type of your property

+4
source

Source: https://habr.com/ru/post/1014670/


All Articles