0

I have to capture DateTime with the following format MM/yyyy. My view-model looks like this

public class SomeViewModel
{
    public string Name { get; set; }

    [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? TargetMonth { get; set; }
}

Then I have razor's editor-template called Date.cshtml with the following code

@model DateTime?
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "form-control", placeholder = ViewData.ModelMetadata.Watermark })

When I select/type value like this 07/2018 I get the following error during the client-side validation

The field Target Month must be a date.

How can I correctly capture the month using the MM/yyyy format?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Junior
  • 11,602
  • 27
  • 106
  • 212
  • Make it a dropdown for month (1 to 12) and make the year a numeric field. I think that is a better UI design. You can restrict min and max for the year too. If you want a single input, use a masked input box and make the property string. Or make the property string and apply regex to it for validation. – CodingYoshi Jul 27 '18 at 23:59

2 Answers2

2

I've replicated your issue on a sample project. The problem is that the DisplayFormat attribute is ignored in TextBox helpers (source).

I would recommend going for an existing datepicker library, there are plenty of good solutions to choose from. I've found a JS Fiddle using Bootstrap Datepicker that addresses your Month picker requirement.

Html:

<input type="text" class="monthPicker" placeholder="CheckIn" >

JS:

$('.monthPicker').datepicker({
    autoclose: true,
    minViewMode: 1,
    format: 'mm/yyyy'
})

You can change your editor template to use this datepicker.

sanfalero
  • 372
  • 2
  • 18
  • The issue is not how to display a picker. The issue on how to bind the value correctly to the view model. I am already using a bootstrap-picker but that just to provide an easy way for the user to select a date. – Junior Jul 27 '18 at 23:52
  • 1
    The issue is that client side validation is not working. I pointed out that this is due to the DisplayFormat being ignored and offered an alternative for client side validation. – sanfalero Jul 28 '18 at 00:41
  • 2
    Maybe I should also point that the DataType.Date client validation is what is causing the client side error you see ("The field Target Month must be a date"). – sanfalero Jul 28 '18 at 01:33
0

You'll want the 'TargetMonth' property on your view model to be a string, not a date. Validate the string to match this regular expression: '[0-1]?[1-9]/[1-2][0-9]{3}'

Then either add a get only property to your data model that parses the string and returns a DateTime instance, or do the conversion logic when you pass the value to its corresponding entity object for storage.

Byron Jones
  • 702
  • 5
  • 11