简体   繁体   中英

MVC date field validation

I'm expecting the user to enter a date in dd-MMM-yyy format. Thus in order to validate user input I use the following in the model

 [DisplayFormat(DataFormatString = "{dd-MMM-yyy}", ApplyFormatInEditMode = true)]
 public DateTime ? SubmittedToDateTime { get; set; }

However, I get the validation error : The field SubmittedToDateTime must be a date. when the user input is : 12-Jun-2013.

I also noted that if change the field value from 12-Jun-2013 to 12 Jun-2013 the error won't appear.

Thanks

yyy won't work. There's yy for two-digit display and yyyy for four-digit display of years. So you've probably missed one y .

As another user mentioned, there's no yyy format. either yy or yyyy for 2 or 4 digit years, respectively.

Also, DataFormatString requires the token index (like a String.Format ) so instead of just the date output, wrap it in the token syntax:

[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]

also, if you really want more control (and not opposed to using jQuery-UI) you can create an edit template for DateTime and use the DatePicker control:

~/Views/Shared/EditorTemplates/DateTime.cshtml

@model DateTime?
@Html.TextBox(String.Empty,  String.Format("{0:dd-MMM-yyyy}", Model.HasValue ? Model : DateTime.Today), new { @class = "datepicker"})

Then you'd have to reference both jQuery & jQuery-UI in the page and add the following somewhere:

<script type="text/javascript">
  $(function(){
    $('.datepicker').datepicker({
      dateFormat: 'dd-M-yy' // http://api.jqueryui.com/datepicker/#utility-formatDate
    });
  });
</script>

Then, in your view, reference @Html.EditorFor(x => x.SubmittedToDateTime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM