English 中文(简体)
未工作的定期表述;MVC3数据发布
原标题:Regular expression for date not working; MVC3 DataAnnotations

Im using DataAnnotations in an interface of a linq sql class. Thats all fine.

与时段有关的问题

我的法典如下:

 [DataType(DataType.Date)]
    [RegularExpression(@"^([1-9]|0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)dd$", ErrorMessage = "regexFail")]
    DateTime? DateofBirth { get; set; }

Now the datatype expression works fine, it brings in a date rather than a date time. The problem lies in validation of the fields. My regex doesn t match dates, even though i put it into an engine and it does. For instance i put "10/10/2010" in the field and i get the error "regexFail".

我确信我的发言是好的,因此我不敢肯定什么错了。

Thanks in advance.

最佳回答

我认为,正在发生的情况是,<代码>Datetime值正在转换成一种扼杀,然后与模式相匹配。 如果使用该词和<代码>ToString,那么在座标上将列入一个 12:00:00 AM的缺省时间。

我尝试了以下代码和IsValid回到true:

string pattern = @"^([1-9]|0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)dds12:00:00sAM$";

RegularExpressionAttribute attribute = new RegularExpressionAttribute(pattern) { ErrorMessage = "regexFail" };
DateTime dt = new DateTime(2010, 10, 10);

bool isValid = attribute.IsValid(dt);
问题回答

Decorating a DateTime field with the [RegularExpression] attribute doesn t make any sense. This attribute is used with string types. When you have a DateTime property the default model binder will use the current culture setting to parse the request value into a DateTime assuming it was a POST request and it will use the yyyy-MM-dd format if it was a GET request. So as you can see it s the default model binder responsible for converting the user HTTP request into an instance of the DateTime field and the RegularExpression validator doesn t come into play.

因此,如果你想要将用户可以进入某些习惯格式的日期限制,你可以使用custom模型对日期

在其他价值类别,如ger和两倍,则相同。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签