1

I asked this question previously while trying to use datepicker to validate a date in asp.net mvc 4.5.1. Now, I have eliminated datepicker and am just trying to validate a date to mm/dd/yyyy format using data annotations in the model and regex to force the format. Here is my code:

Model:
        [DisplayName("Start Date")]
        [DataType(DataType.Date, ErrorMessage = "Date not valid.")]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
        [RegularExpression(@"^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$", ErrorMessage = "Date must be in format mm/dd/yyyy")]
        public DateTime? DT_Project_Start { get; set; }

View:

<div class="form-group">
       @Html.LabelFor(model => model.DT_Project_Start, new { @class = "control-label col-md-2 CreateEditFieldNamesSpan" })
<div class="col-md-10">
       @Html.TextBoxFor(model => model.DT_Project_Start)
       @Html.ValidationMessageFor(model => model.DT_Project_Start)
                            </div>
                        </div>

Doesn't work...validation works perfectly while IN the form, but when I click "submit" it says invalid date NO MATTER what, even if the date is valid and in the right format. Does anyone know what I am missing?

Night Owl
  • 55
  • 2
  • 13
  • Because your property is `DateTime`. Delete the regex (its pointless). You need to modify the `$.validator` method or use `jquery.globalize.js` Refer [this answer](http://stackoverflow.com/questions/27285458/jquery-ui-datepicker-and-mvc-view-model-type-datetime/27286969#27286969) if your using the jquery-ui datepicker –  Nov 16 '15 at 05:51
  • Thanks for the response. If I remove regex, how do I force the client to type in 4-digit year? I am not using datepicker at all at this point. It didn't work with IE. – Night Owl Nov 16 '15 at 06:55
  • Firstly the `[DataType]` and `[DisplayFormat]` are a bit pointless if you use `@TextBoxFor()`. Second you should consider asking a question about the datepicker and IE since there is no reason it should not work. –  Nov 16 '15 at 07:21
  • Also, if you wanting `MM/dd/yyyy`, why are you allowing a `-` as the date separator? –  Nov 16 '15 at 07:25
  • I am really new to asp.net and just learning everything. I have spent a lot of hours trying to get this. Someone gave me the regex and I didn't remove the - in the code, but I will do that! I did have a thread about datepicker, and I got it to work (except for in IE), but I still have to allow for manual input, so still need the 4-digit year to be forced, either way. If @TextBoxFor() doesn't work with [DataType] and [DisplayFormat], what should I use? – Night Owl Nov 16 '15 at 07:49
  • `[DataType]` and `[DisplayFormat]` are only respected when you use `@Html.EditorFor()` but there is nothing wrong with using `TextBoxFor()` (its just that the annotations are unnecessary). But it's a little unclear exactly what your trying to achieve. If the user enters a 2 digit year, it will default to the current century so why are you wanting to force 4 digits? –  Nov 16 '15 at 07:55
  • They work with dates way in the future and past...so "15" could mean "2215", and not "2015". They go back to the 1900's too. Their database is all date-driven, so those dates really need to be correct. Most people will automatically put a 4-digit date if that is the case, but some do not. For the date validation, I just need for it to ensure that the date entered is a valid date, and that the user has entered the year in 4-digit format. What is the best way to achieve that? – Night Owl Nov 16 '15 at 08:14
  • You could always use `[RegularExpression(@".*\d{4}.*"), ErrorMessage="Please eneter a 4 digit year")]` (a `DateTime` has a time component so your current expression always fails) –  Nov 16 '15 at 08:20
  • That worked! I had to write it like this: [RegularExpression(@"^(.*\d{4}.*)$", ErrorMessage="Please enter a 4 digit year")] (a little different), but it DID accomplish what I am looking for! The date itself validates at submission. Thank you!!!! – Night Owl Nov 16 '15 at 08:44
  • @stribizhev, I'm not convinced this is the best approach - will explore it a bit more and add answer later. –  Nov 16 '15 at 08:50
  • In a previous thread, someone gave me a code snippet to add to validate the date and 4-digit year. I did not ever get it to work, but if that's the best approach, I will continue to try to get that to work. Just seems like the built-in validation should somehow do this. Thanks for your help. – Night Owl Nov 16 '15 at 08:55
  • Just out of curiosity, should I change the property to DateTime? Or, should I change the TextBoxFor to EditorFor? Would that help me to accomplish this? – Night Owl Nov 16 '15 at 18:26
  • `DateTime` or `DateTime?` should make no difference. There is no reason to use `EditorFor()` - the main difference is that it will add `type="date"` which will generate the browsers implementation of a HTML5 datepicker. But this is currently only supported in Chrome and Edge (IE and FireFox will just display a normal textbox), and in any case if you do it, then the format string must be `"{0:yyyy-MM-dd}"` (ISO format) and then the date is displayed in the format of the browsers culture. –  Nov 16 '15 at 20:11
  • However you should change the method to `@Html.TextBoxFor(m => m.DT_Project_Start, "{0:MM/dd/yyyy}")` so that the initial display excludes the time component –  Nov 16 '15 at 21:39
  • Do I leave my original regex for 4-digit year? :-) – Night Owl Nov 16 '15 at 21:45
  • I'm looking into datepicker again. I think you helped me with that on my original thread. I think I was using an older version. I upgraded to 1.5.0 and now am trying to make that work again. It looks like, if I configure it correctly, it SHOULD do all this, including validating to 4-digit year?? – Night Owl Nov 16 '15 at 21:53
  • This works inconsistently. I put "1/1/" in the date field and immediately got an error message that it wasn't a valid date. But, then I put "61/1/14" in it accepted it. However, it flagged it when I submitted the record. Why is this so difficult to implement? – Night Owl Nov 17 '15 at 04:40
  • I'm not sure what your problem is or what other mistakes you may have made, but it works fine - refer this [DotNetFiddle](https://dotnetfiddle.net/fRWMiC) –  Nov 17 '15 at 05:01
  • It did work with the regex to validate year only (like your example). You said you didn't think that was the best solution...is it okay to use? That actually worked great! – Night Owl Nov 17 '15 at 05:16
  • Sure its OK to use, but I'm not convinced its the best solution. –  Nov 17 '15 at 05:17
  • It works for this because it is handling the 4-digit year issue, and the server-side validation handles the invalid date issue. Thanks for your help on this. It will work for us until I can figure out datepicker. I have another post about that! Thank you, also, for the example (dotnetfiddle) page! Is there a way for me to give you credit for your help/answer? – Night Owl Nov 17 '15 at 05:44
  • Give me another day to think about other possible solutions and I'll add an answer –  Nov 17 '15 at 05:51
  • I accidentally had one of the dates configured as method "EditorFor" and discovered that having it that way validates the date at the field. Doesn't seem to matter that I have the format string as "{0.MM/dd/yyyy}, it alerts if I type some invalid format like "1/1/". Do you see a problem with leaving it that way? – Night Owl Nov 17 '15 at 07:26
  • Oh never mind...I see what you said above about the date format display. It doesn't work in Chrome...in fact it wipes out my date when I edit the form. – Night Owl Nov 17 '15 at 08:43

1 Answers1

1

If you want to force the user to enter a 4 digit date, you can use the following RegularExpressionAttribute to your property

[RegularExpression(@".*\d{4}.*", ErrorMessage = "Please enter a 4 digit year")]
public DateTime? DT_Project_Start { get; set; }

Note that a DateTime property includes a time component which is why your current regex could fail. Note also that you do not need the [DataType] and [DisplayFormat] attributes. Those are only respected when you use the EditorFor() or DisplayFor() methods. Since your using TextBoxFor(), you can format the date using

@Html.TextBoxFor(m => m.DT_Project_Start, "{0:MM/dd/yyyy}")

to strip the time component from the display.

  • This is working really well so far. Thank you so much for the time and responses that you've given. My votes don't seem to count yet, but as soon as I get a high enough reputation, I'll come back and vote this up! You've been very helpful! – Night Owl Nov 20 '15 at 04:56
  • Do you think that I can add a generic datepicker function to this without validation for ease of entry of the date? – Night Owl Nov 20 '15 at 04:59
  • Sorry, Not sure what you mean by your last comment. –  Nov 20 '15 at 05:00
  • We ultimately would like to have the drop-down calendar on these date fields because it makes entry easier, but they still need to be able to type in the date because dates can be waaaaaay in the future, so I still need the validations. Still need the 4-digit year validation so the type the correct millennium. – Night Owl Nov 20 '15 at 07:35
  • The regex attribute will still work with a datepicker control - for example [jquery-ui datepicker](https://jqueryui.com/datepicker/) –  Nov 20 '15 at 21:44