4

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?

2
  • Not the same but below SO question, the form will render "Required" using Html attribute. Fairly manual approach though stackoverflow.com/questions/6788231/… Commented Nov 23, 2013 at 10:31
  • you can off jquery validation for elements you want and then supply html5 attributes thr. notice data- attributes are part of HTML5.. Commented Nov 23, 2013 at 10:38

1 Answer 1

10

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

@darindimitrov Sir, can you give me advice, what could be the reason that html5 constraint form validation is not working in my mvc 5 web site. Well, actually it kind of working but there is no warning message showing. I have been looking for the solution for three days :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.