Datetime field error message

Asked

Viewed 9,242 times

14

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 appears below the field a message in red:

The field must be a date.

I didn’t implement this, I don’t 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 the 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>
  • You installed the jquery-validate, the globalize and the jquery.globalize in your project?

  • I got the project already started, I can’t tell you. How do I check this? I need to install or uninstall?

  • I’ll give you a little script.

  • What is the file code Shared/EditorTemplates/DateTime.cshtml? What is the HTML generated in your view? <input ... >

  • It puts the input code in which you need to declare the date for us to see and your question becomes clearer !

4 answers

16

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

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 to 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 in your file App_start/Bundleconfig.Cs if there are the following registered Bundles:

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 builds for you. In development environment you can read the original sources. When publishing your website, the codes contained within Bundles are automatically minified.

AsIsBundleOrderer is a file sorter for Bundle. It is used because, as I explained here, the inclusion order of the scripts is not respected, and for this case it is necessary to have an appearance order of these scripts. Its implementation is following.

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

Step 4: Configure View Layout

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

<!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 reticences usually have more code. Try to keep the order of Bundles above, because order is fundamental to the functioning of globalization.

So you don’t need to change anything that has been done and the date validations will work normally.

  • Or use $('#data').removeAttr("data-val-date");

  • 1

    This reference is incorrect: . Include("~/Scripts/jquery.validate.unobstrusive.js"). The right one would be: . Include("~/Scripts/jquery.validate.unobtrusive.js")

6

Four solutions:

Removing the Validationmessagefor

In your view, just below yours

@Html.EditorFor(...)

There must be a code like this:

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

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

Setting a default value for the field

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

Check message after typing date

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

Translating the Message

Another solution is to translate the message, in this MSDN article Voce can see how to do.

Updating

Try using formatting like this:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]

that is, take the ApplyFormatInEditMode = true

Particularly I use only the attribute [DataType(DataType.Date)] do not use the DisplayFormat.

  • I followed the script you passed @Cigano Morrison Mendez and the message was translated into Portuguese, but continues to appear.

  • And yes, @Renatto Machado, the message appears when I’m typing the date. As soon as I just enter the date correctly it disappears. I wish she’d never show up. That only appeared the message I specified in my Model "The start date is mandatory" when the user tried to save without filling in the date field.

  • @Renato Machado, when I use the [Datatype(Datatype.Date)], just selecting the date, no message appears. But as soon as I click on another field to proceed with the completion of the form, the date message appears below the field and stays there until I save.

  • @kLucas vi aqui. This message appears because Voce is using Ajax.BeginForm, so it validates while still typing. Try to do what I told you in my last comment there.

  • @kLucas this form your have to be even Ajax? If there is no need use Html.BeginForm.

  • But that shouldn’t be it @Renatto Machado. Because I have another form that I am not using ajax, I am using: using (Html.Beginform(null, null, Formmethod.Post, new { enctype = "Multipart/form-data" })) and the same thing happens when I start to fill in the date

  • I commented on Scripts.Render("~/Bundles/validation") and the message does not appear when I am typing the date. However no error message appears when I try to save the form leaving the other fields blank. The scripts on it are above

  • @kLucas instead of your code where you have the message: "O campo DataInicio deve ser uma data." let alone "", I believe she’s in your Model.

  • But that’s where it is @Renatto Machado! There’s no phrase in my project. I’ve done a search with the words in every project and there’s no such thing. My model’s message is the one I put up there: "The start date is mandatory" I don’t know where this message comes from, probably a ready-made script that comes automatically

Show 4 more comments

3

3

I had a problem like this recently with the Chrome browser and I 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;
        }
)
  • Please open another question with your question. Do not use the answer space to ask, even if your question is similar.

  • @Gypsy omorrisonmendez I think he’s responding.

  • I agree with @ramaral because of the phrase resolvi colocando este código.

  • Now it’s all right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.