Short date submission not working abbreviated asp.net mvc

2

I am creating a form in ASP.NET MVC and creating the field "DataMessage", at first I put the TextBox to load a date with the month in full, as below:

Imageoftheformwiththefield"Date of the message" containing the month in extenso.

Image of the form with the field "Message date" containing the month in full.

Below, the View code for the "Message Date" field:

Imageofthecodeusedtocreatethe"Message Date" field with the month in full Image of the View code used to create the "Message Date" field with the month in full.

When I create the field in this way, in addition to loading correctly, I can seamlessly send data to the database in case of a possible change.

However, when I use the format to abbreviate the Month and only display the Month's number, the validation does not allow me to send the same to the database in case of a possible message change.

Below, the form with the "Message date" field loaded correctly with the abbreviated month:

Imageoftheformwiththe"Message date" field containing the abbreviated month, with the error displayed when clicking the "Save" button.

Image of the form with the "Message date" field containing the abbreviated month, with the error displayed when clicking the "Save" button.

Below, the View code for the "Message Date" field with the abbreviated month: Image of the View code used to create the" Message Date "field with the abbreviated month. Image of the View code used to create the "Message Date" field with the abbreviated month.

And below, the model used for the "Message Date" field:

Modelofthe"Message Date" field.

Model of the "Message Date" field.

Does anyone know why this problem is happening and how can I resolve it? Thanks in advance.

    
asked by anonymous 28.06.2017 / 19:26

1 answer

1

Your problem is related to the browser that understands that the first field of the date is the month, you can test any value over 12 that will generate the same problem as it tries to do a parse for month and understands that the value is invalid.

You may notice that if you put 01/02/2017, asp.net will correctly receive day 01 and month 02, confirming that the validation problem is only client-side.

I found a snippet (#

<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

    $(function () {
        $.validator.methods.date = function (value, element) {
            if ($.browser.webkit) {

                //ES - Chrome does not use the locale when new Date objects instantiated:
                var d = new Date();

                return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
            }
            else {

                return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
            }
        };
    });
</script>
    
11.11.2017 / 16:39