2

My SQL database has a column Date which allows strings only in such format: __/____, basically month/year for example: 01/2019.

Is it possible for my:

@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })

to have some helper so that user can type only using the correct format? For example the editor which has strong typed something like this: __/___ and can only input numbers to fill underscores.

Pomme
  • 87
  • 8
  • 3
    If you changed your database and model to store a date rather than a string (which I would advise anyway), I think you could use the technique in [this answer](https://stackoverflow.com/a/36014557/1048425). – GarethD Jul 31 '19 at 12:03
  • The data format for the field in user interface and data storage can be independant . You should show the date in the users locale and convert to the format before saving to database – PeterHe Jul 31 '19 at 15:00
  • 1
    Would this help: ``? (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/month) – Alex Jul 31 '19 at 16:33
  • @Alex not so much because SQL stores the value as nvarchar in such format. – Pomme Aug 01 '19 at 06:21
  • @GarethD if I change the datatype to `DateTime` will I be able to use @Alex approach to input `month` for it? – Pomme Aug 01 '19 at 06:37
  • @Pomme read the linked page. It explains near the bottom that the control's value is a string in `yyyy-MM` form. A far better form than `MM/yyyy` as it can handle ordering, range queries etc. If you want to convert it to `MM/yyyy` you can use a regex or string manipulation to switch the parts – Panagiotis Kanavos Sep 12 '19 at 14:29
  • @Pomme besides, you don't have a date to begin with, just a string. Date types in SQL have no format, nor can they store just a month without a day. – Panagiotis Kanavos Sep 12 '19 at 14:30

1 Answers1

0
@Html.TextBoxFor(m => m.StartDate, 
    new { @Value = Model.StartDate.ToString("yyyy/MM/dd"), @class="datepicker" })