开发者

ASP.NET MVC2 Strange Validation Problem with Regex (DataAnnotations)

I've got my validation wired up through my Service layer, and my Birthdate property looks like this.

    <DisplayName("birthdate")> _
    <RegularExpression("^\d{2}\/\d{2}\/\d{4}$", ErrorMessage:="Birthdate is not in the correct format.")> _
    <DisplayFormat(ApplyFormatInEditMode:=True, ConvertEmptyStringToNull:=True, DataFormatString:="{0:MM/dd/yyyy}")> _
    Public Property BirthDate As DateTime

The client side validation works properly if I input something like 12/12/1990 but when the form is submitted, the server side validation trips and I'm told the entry is invalid. I'm using the jQuery-UI Datepicker to input the date, however when I disable the datepicker, the problem persists.

Am I missing something here? I thought the client side and server side would be the same thing.

Afterthought.

Could it be because I'm using datetime2(0) in my SQL Server database?

I tested the above theory to no avail... same problem.

EDIT:

If I remove

<RegularExpression("^\d{2}\/\d{2}\/\d{4}$", ErrorMessage:="Birthdate is not in the correct format.")>

Then the form submits. It's obviously something to do with the Regex.

EDIT:

The following code doesn't work either, but I'm wondering if there is a way to modify the modelState to properly se开发者_开发百科t the date before it's passed to the IsValid method?

    Dim birthdate As String = user.BirthDate
    ModelState.Item("BirthDate") = DateTime.Parse(birthdate)


Suppose the user enters 06/27/2010 in the text field and submits the form.

  1. The default model binder runs and tries to bind what the user entered to your model. The BirthDate property is of type DateTime and as you know this type contains an hour part. So now BirthDate = 6/27/2010 12:00:00 AM

  2. Validation kicks in next. The BirthDate property is decorated with the RegularExpression attribute so the IsValid method is called with the string value of 6/27/2010 12:00:00 AM which fails against your pattern.

  3. The corresponding error message is shown to the user.

So the usage of this regular expression attribute is questionable. RegularExpressionAttribute works fine with string properties though.

If the user enters an invalid date the model binder will protest anyway much before the validation happens. It will also check for invalid days and months which your regular expression doesn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜