Error message in datetime field

10

I have a field in my application in mvc asp.net c # to put start date and end date.

    [Required(ErrorMessage = "A data de início é obrigatória")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime DataInicio { get; set; }

However, while the user is typing the date a red message appears below the field:

  

The field must be a date.

I did not implement this, I do not know where it comes from. Does anyone know how to disappear with this alert?

View

@model Competências.Models.Experiencia

@Scripts.Render("~/bundles/validation")

@using (Ajax.BeginForm(new AjaxOptions
                {
                    InsertionMode = InsertionMode.Replace,
                    HttpMethod = "POST"
                }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<div class="modal-body row">
    <div class="col-md-7">
     @Html.LabelFor(model => model.Nome)
       @Html.TextBoxFor(model => model.Nome, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Nome)
    </div>
      <div class="col-md-5">
       @Html.LabelFor(model => model.Funcao)
       @Html.TextBoxFor(model => model.Funcao, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Funcao)
    </div>

</div>
    <div class="modal-body row">

    <div class="col-md-4">
        @Html.LabelFor(model => model.DataInicio)   
        @Html.EditorFor(model => model.DataInicio, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.DataInicio)
    </div> 

    <div class="col-md-4">
        @Html.LabelFor(model => model.DataFinal)       
        @Html.EditorFor(model => model.DataFinal, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.DataFinal)
    </div>


    </div>

<div class="modal-footer">

    <input class="btn btn-primary" type="submit" value="Salvar" />
    <a class="btn btn-default" onclick="FechaModal();">Cancelar</a>
</div>


}

Input generated in browser

<div class="modal-body row">

    <div class="col-md-4">

         <b>Data de Início</b> 
        <input class="text-box single-line" data-val="true" data-val-date="O campo DataInicio deve ser uma data." data-val-required="A data de início é obrigatória" id="DataInicio" name="DataInicio" type="date" value="">
        <span class="field-validation-valid" data-valmsg-for="DataInicio" data-valmsg-replace="true"></span>
    </div> 

    <div class="col-md-4">

        <b>Data Final</b>
        <input class="text-box single-line" data-val="true" data-val-date="O campo DataFinal deve ser uma data." data-val-required="A data de início é obrigatória" id="DataFinal" name="DataFinal" type="datetime" value="">
        <span class="field-validation-valid" data-valmsg-for="DataFinal" data-valmsg-replace="true"></span>
    </div>

    <div class="col-md-3">



</div>

    </div>
    
asked by anonymous 02.07.2014 / 18:19

4 answers

13

The problem happens because an ASP.NET MVC project comes configured with the en-US culture by default. This validation message is made by jQuery using Unobtrusive Ajax and Validation , which need to be coupled to a globalization plugin to work properly. p>

Step 1: Install Globalization Packages

In Visual Studio, go to View > Other Windows > Package Manager Console .

Install the following packages, using the commands below:

  

PM > Install-Package jQuery.Validation.Globalize

     

PM > Install-Package jquery-globalize

Step 2: Configure Web.config to use settings in English

Add the following in your web.config :

<configuration>
    <globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" requestEncoding="UTF-8" responseEncoding="UTF-8" fileEncoding="UTF-8" />
</configuration>

pt-PT also works, if it is the desire of the programmer to use the culture in Portuguese of Portugal.

Step 3: Configure Bundles

Check your App_Start / BundleConfig.cs file if the following Bundles are registered:

public class BundleConfig
{
    // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.IgnoreList.Clear();

        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js",
                    "~/Scripts/jquery.replace-text.js"));

        var bundle = new ScriptBundle("~/bundles/jqueryval") { Orderer = new AsIsBundleOrderer() };

        bundle
            .Include("~/Scripts/jquery.unobtrusive-ajax.js")
            .Include("~/Scripts/jquery.validate-vsdoc.js")
            .Include("~/Scripts/jquery.validate.js")
            .Include("~/Scripts/jquery.validate.unobtrusive.js")
            .Include("~/Scripts/globalize/globalize.js")
            .Include("~/Scripts/jquery.validate.globalize.js");
        bundles.Add(bundle);
    }
}

Bundles are portions of code that ASP.NET MVC mounts for you. In development environment you can read the original sources. When you publish your site, the codes contained within Bundles are automatically minified.

AsIsBundleOrderer is a computer of Bundle files. It is used because, As explained here , the order of inclusion of the scripts is not respected, and in this case you must have an order of appearance of these scripts. Your implementation is set to follow.

public class AsIsBundleOrderer : IBundleOrderer
{
    public IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
    {
        return files;
    }
}

Step 4: Configure Views Layout

Make sure these Bundles are in the Views / Shared / _Layout.cshtml file:

<!DOCTYPE html>
<html>
<head>
    ...

    <title>@ViewBag.Title - Seu site</title>
    ...

    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/jqueryval")
    ...
    @RenderSection("scripts", required: false)
    @Flash.FlashMessage(TempData)
</head>

The places where I put ellipsis usually have more code. Try to maintain the order of the Bundles above, because order is critical to the functioning of globalization.

So you do not need to change anything that has been done and the date validations will work normally.

    
02.07.2014 / 19:09
4

Four solutions:

Removing ValidationMessageFor

In your view, just below your

@Html.EditorFor(...)

It should have a code like this:

@Html.ValidationMessageFor(model => model.DataInicio)

It is this code that generates the validation you are seeing.

Defining a default value for the

Now the solution may not be to take this validation, but to treat. One suggestion I give you is to fill in this date automatically on your Controller.

Check message after typing date

Have you checked if after entering the entire date if the message disappears? It may be that the message is shown only while entering the date.

Translating the Message

Another solution is to translate the message, this MSDN article

02.07.2014 / 19:02
1

I recently had a problem with the Chrome browser and decided to put this code:

$.validator.addMethod('date',
        function (value, element, params) {
            if (this.optional(element)) {
                return true;
            }

var result = true;
            try{
                $.datepicker.parseDate('dd/mm/yy', value);
            } catch (e) {
                    result = false;
            }

            return result;
        }
)
    
06.11.2014 / 21:42
0

The only thing that worked for my date in dd/mm/yyyy format was:

// Corrects the chrome validation BUG of the Date field in the format dd / mm / yyyy

// source link

jQuery.validator.methods.date = function (value, element) {     return this.optional (element) || moment (value, "DD / MM / YYYY", true) .isValid (); };

    
11.07.2017 / 15:09
What is the difference between GraphQL and REST? ___ ___ erkimt What are the data transfer forms available to JavaScript? ______ qstntxt ___

It is common to find questions, answers and tutorials talking about AJAX, which is nothing more than %code% , as a way of transferring data between two computers.

I would like to know if there are other forms , whether standard or proprietary, limited in some condition or open to any user and site. An example of a limited form, if any, would be an API restricted to extensions.

In particular, but not restricting, I'm looking for a way to transfer data - something between 10 and 30 bytes - in the fastest way possible between two computers within the same network. Peer-to-Peer would be ideal, but I do not know if JS supports it. I have already tried testing services such as Firebase , which allowed a minimum response time, however, using a server out of network and with occasional loss of data.

Knowing other ways I wanted to find one that would fit better with what I'm developing. It does not look like the answer will be anything big: the options seem to be quite limited, since it looks like only AJAX is used.

    
______ azszpr8188 ___

There are several APIs that will allow you to transport data via Javascript.

Some will only allow you to receive data, others will allow you to send and receive.

The ones that allow you to send and receive data are:

  • %code%
    • Requests via HTTP protocol
  • %code%
    • It is a cross-compatible HTTP protocol focused on message exchanges lighter and faster than request, but it does not have a state resolution as efficient as %code%
    • W3C Specification
  • %code%
    • Peer-to-peer data exchange protocol was created to solve the problem of video and audio transmissions between browsers.
    • W3C Specification

If the data transmission needs to be p2p, the ideal is to use WebRTC, but it is still rather complex to create a server that will make the handshake between two browsers and start communication.

A simpler solution is to use WebSockets , but all information will go through a server that will receive data from one client and send it to another or other clients. But the websocket has the constraint of working with UTF-8, however it is possible to use data converters to convert binary data to UTF-8 before being transmitted and back to the original format when received, there are several ways, one of them is using the %code% .

    
______ azszpr8194 ___

I suggest using Socket IO, a javascript extension already adapted for use in cross-browser and that has an extra advantage, it chooses the most efficient way to carry data between the technologies below (which are the answer to your question) :

1) WebSocket;
2) Adobe Flash Socket;
3) AJAX long polling;
4) AJAX multipart streaming;
5) Forever iframe;
6) JSONP Polling.

Still, this extension has excellent compatibility: IE 5.5+; Safari 3+; Chrome 4+; Firefox 3+; Opera 10.61+; Iphone / Ipad Safari; Android Webkit and Webkits Webkit.

link

I have had excellent experiences with this extension. When you opt for a path where fallbacks are already included, everything gets easier!

Good Luck!

    
___