Graham Conzett
Graham Conzett

Reputation: 8454

asp.NET MVC Model State Validation Issues

I am having issues adding validation methods to a couple of controls in my MVC app. I use the following to test for the mm/dd/yyyy format:

if (!Regex.IsMatch(candidateToEdit.availability.StartDate.ToShortDateString(), @"giantregex"))
            ModelState.AddModelError("availability_StartDate", "Start date must be in the mm/dd/yyyy format.");
//giantregex is a giant regular expression omitted for clarity

In my view I have:

<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>

<%= Html.ValidationMessage("availability_StartDate", "*")%>

For whatever reason the error text is not being displayed, it acknowledges there is an error and the start of the list is generated, but the "Start date must be in the mm/dd/yyyy format." is not displayed. It validates if you put in the date correctly.

Upvotes: 0

Views: 4190

Answers (3)

cfeduke
cfeduke

Reputation: 23236

I think the problem here is you're testing an actual DateTime type against a regular expression. Because they have entered an invalid date time format in the text box, it is never actually parsed into an actual DateTime where ToShortDateString() could be invoked on it. Therefore your regular expression validation is never actually occurring.

You'll need to adopt the ViewModel pattern where you expose all potential parsing problems as strings first (such as "candidateToEditViewModel.AvailabilityStartDateString") or implement client side validation and program defensively.

Upvotes: 3

Mathias F
Mathias F

Reputation: 15931

The sample you gave works at my testproject. Can you try to reproduce the error in a freshly created project?

Upvotes: 0

Josh E
Josh E

Reputation: 7432

I think you need to include a validation summary to get the message

<%= Html.ValidationSummary() %>

EDIT: Try putting a "." instead of a "_" as your property name in the AddModelError call, like this:

Instead of:

ModelState.AddModelError("availability_StartDate", "Start date must be...");

try this:

ModelState.AddModelError("availability.StartDate", "Start date must be...");

Upvotes: 0

Related Questions