How can I specify the order of the DataAnnotation ValidationAttribute?

The question here is similar, but I have no inheritance of domain objects. My fields and validation tags are in the following order, but MustBe18 errors and a mandatory error are the only ones that print. I have several other fields in this model with much more validation, but the order of the ValidationAttribute in the code does not seem important. Jfar's answer in a related post seems to suggest that an assistant can be built, but how? How can order be controlled?

[Required(ErrorMessage = "This field is required")] [DisplayName("Date of Birth")] [MustBeValidDate(ErrorMessage = "Must be a valid date")] [MustBe18(ErrorMessage = "You must be 18 years old")] [MustNotBeOver100(ErrorMessage = "This caller is too old")] public string dob { get; set; } 

MustBe18: ValidationAttribute (Overloaded IsValid Method)

 try { DateTime dob = new DateTime(DateTime.Now.AddYears(-18).Year, DateTime.Now.Month, DateTime.Now.Day); return DateTime.Compare(DateTime.Parse(value.ToString()), dob) <= 0; } catch { return false; } 
+4
source share
1 answer

The only way to specify an order is to create your own ModelValidatorProvider , which can then order attributes. This will probably be difficult, because you also need to create overloads for each attribute that accepts the Order parameter (I don’t know if they are already running).

If you all mind, this is the order in which the validation summaries are displayed, all you have to do is loop through the ModelState entries and spit out the errors from there.

+3
source

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


All Articles