MVC HTML Helpers: Get all validation attributes

1.8k views Asked by At

When it comes to making custom helpers, how can we get the value for the validation attributes (client-side validation)? for example the built in helpers do something like this:

<label class="control-label " for="Starts">Starts</label>
<span class="field-validation-valid text-danger" data-valmsg-for="Starts" data-valmsg-replace="true"></span>
<input class="form-control text-box single-line" data-val="true" data-val-date="The field Starts must be a date." data-val-required="The Starts field is required." id="Starts" name="Starts" type="date" value="" />
<br />

so now in my custom helper I should determine the validation type data-val-date for example and validation messages. The ModelMetaData does not have any property for that. How could this be done ?

1

There are 1 answers

0
Transcendent On BEST ANSWER

the values like the error message, etc, are exactly what I need.

As Stephan said in his comment, you don't have to go after getting the values for such data annotation attributes as it will be only and only duplication of work. If you really wanna encapsulate your form in a single helper, then why not re-using the beautiful built-in helpers?

To show you an example for what I mean:

public static MvcHtmlString MyFastHelper<T,R>(this HtmlHelper<T> helper, Expression<Func<T,R>> selector, Boolean validate = false){
     var Label = LabelExtensions.LabelFor(helper, selector);
     var Val = ValidationExtensions.ValidationMessageFor(helper, selector);
     var Editor = EditorExtensions.EditorFor(helper, selector, new { htmlAttributes = new { @class = "form-control"} });
     if (validate)
     {
         return new MvcHtmlString(String.Format("{0}\r\n{1}\r\n{2}\r\n</br>", Label.ToHtmlString(), Val.ToHtmlString(), Editor.ToHtmlString()));
     }
     else
     {
         return new MvcHtmlString(String.Format("{0}\r\n{1}\r\n</br>", Label.ToHtmlString(), Editor.ToHtmlString()));
     }
}

Or if you are really interested in knowing how these built-in helpers work, you can sneek into the the .NET by using softwares such dotPeek. You can get it Here