Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 5 and HTML 5 form attributes according to the W3C specs

As for as I know it seems like Microsoft are using jQuery validation attributes as default for form input attributes.

Is it possible to configure my application so if I add the Required attribute and render my form using @Html.EditorFor(x => Model) the form will be rendered using required attributes instead of data-val-required? Or am I forced to write my own EditorTemplates for all standard types?

like image 400
marcus Avatar asked Dec 26 '22 17:12

marcus


1 Answers

If you want to replace the standard data-* validation attributes used by ASP.NET MVC you should start by disabling unobtrusive client side validation in your web.config:

<add key="ClientValidationEnabled" value="false" />

This will prevent the html helpers from emitting them on your input fields.

Then you could write custom editor templates for the standard types. For example for string that would be ~/Views/Shared/editorTemplates/String.cshtml:

@{
    var attributes = new Dictionary<string, object>();
    attributes["class"] = "text-box single-line";
    if (ViewData.ModelMetadata.IsRequired)
    {
        attributes["required"] = "required";
    }
}

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, attributes)

And that's pretty much it. Now everytime you do an Html.EditorFor(x => x.Foo) where Foo is a string property it will generate the following markup:

<input class="text-box single-line" id="Foo" name="Foo" required="required" type="text" value="" />

It's also worth mentioning that if you don't want to disable unobtrusive client side validation and the data-* attributes for your entire application but only for a single form you could do that:

@using (Html.BeginForm())
{
    this.ViewContext.ClientValidationEnabled = false;
    @Html.EditorFor(x => x.Foo)
}
like image 56
Darin Dimitrov Avatar answered Dec 29 '22 10:12

Darin Dimitrov