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.
The default model binder runs and tries to bind what the user entered to your model. The
BirthDate
property is of typeDateTime
and as you know this type contains an hour part. So nowBirthDate = 6/27/2010 12:00:00 AM
Validation kicks in next. The
BirthDate
property is decorated with theRegularExpression
attribute so theIsValid
method is called with the string value of6/27/2010 12:00:00 AM
which fails against your pattern.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.
精彩评论