El campo fecha debe ser una fecha en mvc en chrome [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Estoy haciendo una simple aplicación de Internet MVC4, que permite agregar algunos elementos a las categorías.

Esto es lo que he hecho hasta ahora.

Tengo un datepicker en la vista mvc. El script para el datepicker es así.

<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
    $(function () {
        $('#dtItemDueDate').datepicker({
            dateFormat: 'dd/mm/yy',
            minDate: 0
        });
    });
</script>

Mi modelo propiedad :

        [DisplayName("Item DueDate")]
        [Required]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]
        [DataType(DataType.DateTime)]
        public DateTime? dtItemDueDate { get; set; }
        public char charCompleted { get; set; }

Y en mi opinión he hecho esto:

@Html.TextBoxFor(m => m.dtItemDueDate)
@Html.ValidationMessageFor(m => m.dtItemDueDate)

El error es así:

The field Item DueDate must be a date.

Lo extraño es que funciona en IE y Mozilla, pero no funciona en Chrome.

Encontré muchos mensajes en SO, pero ninguno de ellos ayuda

¿Alguna idea/sugerencia ?

Author: Karthik Chintala, 2013-03-29

6 answers

Nota del editor: Esta respuesta ya no es válida, a partir de jQuery 1.9 (2013) el método $.browser se ha eliminado


De acuerdo con este post es una peculiaridad conocida con los navegadores basados en Webkit.

Una solución es modificar jquery.validate.js encontrando la función date: function (value, element) y poner este código en ella:

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));
}
 30
Author: Rowan Freeman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:46:57

Sin cambiar jquery.validar.js, puede usar el recorte de código a continuación en $(document).ready():

jQuery.validator.methods.date = function (value, element) {
    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    if (isChrome) {
        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));
    }
};
 42
Author: Mahesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 02:56:16

La solución de Rowan Freeman no funcionará para mí ya que .toLocaleDateString(value) no analiza value cadenas

Aquí está la solución que se me ocurrió => en jquery.validar.js encuentra esta definición de función: "date: function (value, element)" y reemplaza el código con:

// http://docs.jquery.com/Plugins/Validation/Methods/date
date: function (value, element) {
    var d = value.split("/");
    return this.optional(element) || !/Invalid|NaN/.test(new Date((/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) ? d[1] + "/" + d[0] + "/" + d[2] : value));
},
 7
Author: Chtiwi Malek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-31 10:56:18

A continuación se muestra el código de trabajo que puede ser útil para alguien para solucionar el problema del selector de fecha en chrome y safari: Modelo:

public DateTime? StartDate { get; set; }

Vista:

@Html.TextBoxFor(model => model.StartDate, "{0:dd/MM/yyyy}", new { @type = "text", @class = "fromDate" })

Js:

$(function () {
    checkSupportForInputTypeDate();

    $('#StartDate').datepicker({        
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy'
    });    
});

//Function to configure date format as the native date type from chrome and safari browsers is clashed with jQuery ui date picker.
function checkSupportForInputTypeDate() {
    jQuery.validator.methods.date = function (value, element) {
        var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
        var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
        if (isSafari || isChrome) {
            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));
        }
    };
}
 7
Author: KSK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-10 09:51:03

Aquí está La solución de Maxim Gershkovich deletreada un poco más:

jQuery.validator.methods.date = function (value, element) {
    if (value) {
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        } catch (ex) {
            return false;
        }
    }
    return true;
};

Notas:

  • Esto depende del método jQuery datepicker que viene con jQuery UI
  • Esto es en realidad más robusto que la validación de fecha nativa que viene con jQueryValidate.

    De acuerdo con los documentos en fecha de validación :

    Devuelve true si el valor es una fecha válida. Utiliza la fecha incorporada de JavaScript para probar si la fecha es válida, y por lo tanto no hace controles de cordura. Solo el formato debe ser válido, no la fecha real, por ejemplo, 30/30/2008 es una fecha válida.

    Considerando parseDate comprobará que la fecha es válida y realmente existe.

 7
Author: KyleMit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:25

Resolví este problema cambiando de DateTimea String.

Esta es la mejor solución para un buen mantenimiento que puedo pensar en este momento.

 0
Author: alansiqueira27,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-15 16:55:33