Validate fields with html 5 and mvc 5

2

As I validate fields in CSHTML itself, that when I click the button, it validates the fields and if there are fields not filled it remains on the page, displaying a message. See the sample fields and the button to validate.

<div class="form-group">
    <div class="grid_4">
        <label>Nome</label>
    </div>
    <div class="grid_14">
        <input type="text" name="txtNome" class="grid_14 required" placeholder="Nome completo" required />
    </div>
</div>
<div class="form-group">
    <div class="grid_4">
        <label>Email</label>
    </div>
    <div class="grid_7">
        <input type="email" name="txtEmail" class="grid_6  required" placeholder="Email válido" required />
    </div>
    <div class="grid_2">
        <label>CPF</label>
    </div>
    <div class="grid_5">
        <input type="number" name="txtCpf" class="grid_5  required" placeholder="99999999999" required />
    </div>
</div>

//Botão

<div class="grid_17">
    <button value="novaPesquisa" class="btn-pular-passo pull-right">Continuar</button>
</div>
    
asked by anonymous 13.03.2014 / 22:54

2 answers

4

No , the validation is done by decorating the properties of its Model with the appropriate attributes.

Examples:

  • [Required] : Makes the property mandatory.
  • [StringLength(60)] : Makes String property a maximum of 60 characters.

In order for validations to work properly, you need to use the following code in Razor right after the <input> of your property:

@Html.ValidationMessageFor(model => model.SuaProperty)
    
13.03.2014 / 23:02
2

What you're looking for is not the Microsoft jQuery Unobtrusive Validation library? Add it via NuGet.

Enable in web.config and test.

In web.config is this property you need to enable:

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

I even tried it here, but at the time of installing it it gave jQuery incompatibility error. Even uninstalling jQuery and installing it, then letting it resolve jQuery's dependency, it still gave trouble.

So if you have a problem remove jQuery, first install jQuery Validation, and then install Microoft jQuery Unobtrusive Validation.

This here for me solved the incompatibility.

EDITION

Do not forget to add the jQuery Validation plugins to the View. To follow the pattern you need to add them in the BundleConfig.cs inside the App_Start folder.

bundles.Add(new ScriptBundle("~/js/jqueryval").Include(
    "~/Scripts/jquery.validate.*"));

And then add in the view the call to these scripts:

@Scripts.Render("~/js/jqueryval")

Done this has to work.

    
13.03.2014 / 23:25