Reputation: 1565
I've created a DatePickerFor Helper but it is not getting the validators of my ViewModel.
My viewmodel:
public class Dates
{
public DateTime ExpiringDate { get; set; }
[Required(ErrorMessage = "This field is required!")]
[LessThan("ExpiringDate")]
public DateTime Start { get; set; }
}
My helper:
public static MvcHtmlString DatePickerFor(this HtmlHelper helper,Expression<Func<TModel, TProperty>> expression /*, Some args*/)
{
StringBuilder html = new StringBuilder();
html.Append("<div class=\"input-group\">");
html.Append("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
html.Append("<input id=\"" + id + "\" type=\"text\" name=\"" + name + "\" value=\"" + dateValue + "\" class=\"form-control datepicker " + cssClass + "\" data-dateformat=\"dd/mm/yy\" placeholder=\"00/00/0000\" " + attrs + "/>");
html.Append("</div>");
return new MvcHtmlString(html.ToString());
}
Is possible to have "data-val-required" and others validations defined in the viewmodel added to my html?
Thanks!
Upvotes: 0
Views: 408
Reputation: 8188
you can try to override the default TextBoxFor helper and extend the output with your custom properties
public static MvcHtmlString DatePickerFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
var extendedAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
extendedAttributes.Add("class", "form-control datepicker");
extendedAttributes.Add("data-dateformat", "dd/mm/yy");
extendedAttributes.Add("placeholder", "00/00/0000");
return htmlHelper.TextBoxFor(expression, extendedAttributes);
}
Upvotes: 1