Form validation with MVC Dataannotations

Asked

Viewed 499 times

1

I’m trying to validate forms with use of Dataannotation, I tried direct on model or in my viewmodel and none of them works.

View Model:

public class CieloViewModelTransacaoPartial
{
    [Required(ErrorMessage = "Token é obrigatório")]
    public string Token { get; internal set; }

    [Required(ErrorMessage = "IDC é obrigatório")]
    [Display(Name = "IDC")]
    public int ClienteId { get; set; }

    [Required(ErrorMessage = "Valor a ser cobrado é obrigatório")]
    [Range(1, 50000)]
    public decimal Valor { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    [Required(ErrorMessage = "Data de Refêrencia é obrigatórico")]
    [Display(Name = "Data de Refêrencia")]
    [DataType(DataType.Date)]
    public DateTime DataRef { get; set; }

    public int Tipo { get; set; } //1 config, 2mensal, 3 outros, 4 diff. mensal
}

View Resumida:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="panel-body">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-horizontal">
            <div class="form-group">
                @Html.LabelFor(model => model.Token, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Token, new { htmlAttributes = new { @class = "form-control" } })

                    @Html.ValidationMessageFor(model => model.Token, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.ClienteId, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-4">
                    @Html.EditorFor(model => model.ClienteId, new { htmlAttributes = new { @class = "form-control form-peq" } })

                    @Html.ValidationMessageFor(model => model.ClienteId, "", new { @class = "text-danger" })
                    <a href="#" onclick="CarregarJSON();">Carregar cliente</a>
                </div>
                <div class="col-md-6 pull-left">
                    <div id="ClienteUrl"></div>
                </div>
            </div>
        </div>
        <div class="panel-footer">
            <div class="pull-right">
                <input type="submit" value="Cadastrar" class="btn btn-danger " /></div>
        </div>
    </div>
}

and my _Layout already calls the javascript below:

inserir a descrição da imagem aqui

But he’s posting without validating. No console error or error. I want to validate in the browser with Dataannotation, what is missing?

update: _Layout code

<body class="@ViewBag.PageClass @WMB.App_Helpers.Settings.CurrentTheme">
    @{ Html.RenderPartial("_Header", RenderSection("topright", false)); }
    @{ Html.RenderPartial("_Aside"); }
    <div id="main" role="main">
        @{ Html.Partial("_Ribbon"); }
        @RenderBody()
    </div>
    @if (Request.IsAuthenticated)
    {
        Html.RenderPartial("_Footer");
    }


    @{ Html.RenderPartial("_Scripts"); }
     @RenderSection("pagespecific", false)
</body>

and the _Scripts.cshtml page

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script> if (!window.jQuery) { document.write('<script src="/scripts/jquery-2.2.0.min.js"><\/script>'); } </script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script> if (!window.jQuery.ui) { document.write('<script src="/scripts/libs/jquery-ui-1.11.4.min.js"><\/script>'); } </script>

<!-- IMPORTANT: SmartAdmin Core -->
@Scripts.Render("~/scripts/smartadmin")

<!-- DO NOT REMOVE : GLOBAL FUNCTIONS! -->
<script>
    $(document).ready(function () {
        pageSetUp();
        drawBreadCrumb();
    });
$(document).ready(function () {
    pageSetUp();
    drawBreadCrumb();
});
function MostraConfirm(title, texto) {
    $.bigBox({
        title: title,
        content: texto,
        color: "#78C469",
        //timeout: 6000,
        icon: "fa fa-warning shake animated",
        number: "1",
        timeout: 6000
    });

}
</script>

@if (@Model is HelperResult)
{
    @Model
}
  • Recalling that the jQuery.val is the validation in View. In his controler is checking out the ModelState?

  • I want to validate only in the view, in the controller is ok.

  • I saw you referencing the jQuery, but is not referencing the jQuery.validade.js nor the jquery.validade.unobtrusive.js. That’s probably the problem.

1 answer

1


The mistake was the lack of 2 key in the web.config

  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

As described in detail http://www.macoratti.net/12/07/mvc_valid1.htm

Browser other questions tagged

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