Organizational Research By

Surprising Reserch Topic

validate a date in a specific format in asp net mvc 3

validate a date in a specific format in asp net mvc 3  using -',,validation,'

I have a property of type DateTime MyDate in my ViewModel. I want to make sure that the user only enters the Date part in a text box in a specific format ( and tried the following attributes:

[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode=true)]
public DateTime MyDate { get; set; }

The controller action signature for a HttpPost looks like this:

public ActionResult Edit(int id, MyViewModel viewModel)
    // MyViewModel contains the MyDate property ...
    // ...
    if (ModelState.IsValid)
        // ...
    // ...

In the Razor view I tried the following two ways:

@Html.TextBoxFor(model => model.MyDate)
@Html.EditorFor(model => model.MyDate)

It doesn't work as I want. The result is:

Client side validation works as expected with both Html helpers
Server side validation always fails for both helpers, even with valid dates like "17.06.2011" which pass the regular expression. The MyDate property is filled correctly with the entered date in viewModel which is passed to the action. So it seems that model binding was working.
The DisplayFormat attribute is only respected by EditorFor but not by TextBoxFor. TextBoxFor displays " hh:mm:ss"


Can I apply a RegularExpressionAttribute at all on a property which isn't a string? If it is allowed how is the reg ex evaluated for a non-string property like DateTime on server side? Is something like MyDate.ToString() compared with the reg ex? (It would explain that the validation fails because ToString will return a string including time part which doesn't pass the regular expression.)
Is the DisplayFormat attribute generally only respected by EditorFor and never by TextBoxFor?
How can I do a date validation right?


asked Oct 7, 2015 by sandeep bhadauria
0 votes

Related Hot Questions

2 Answers

0 votes
answered Oct 7, 2015 by tejas lakhani
0 votes
answered Oct 7, 2015 by patelnikul321