I am very new to MVC 3.
I am using custom helpers for the controls but when i submit the form, the control is not being validated.
Can some one tell me if i am missing something? Following is the code snippet.
public static MvcHtmlString TextBox(string fieldName)
{
TagBuilder tagBuilder = new TagBuilder("Input");
tagBuilder.MergeAttribute("type", "Text");
tagBuilder.AddCssClass("text-box");
tagbuilder.MergeAttribute("data-val","true");
tagbuilder.MergeAttribute("data-val-regex-pattern","true");
tagbuilder.MergeAttribute("data-val","true");
TagBuilder validator = new TagBuilder("span");
validator.MergeAttribute("data-valmsg-for", fieldName);
validator.MergeAttribute("data-valmsg-replace", "true");
validator.MergeAttribute("class", "field-validation-valid");
return new MvcHtmlString(string.Concat(tagBuilder.ToString(), validator.ToString()));
}
The view has the following code
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<div class="main-border" style="width: 890px;">
<div style="clear: both;">
</div>
<div style="padding: 0px 20px 0px 20px;">
<table style="width: 100%">
<tr>
<td colspan="2" class="main-subhead2">
<div class="label-text">
</div>
</td>
</tr>
<tr>
<td>Email :</td>
<td>@ControlHelper.TextBox("txtEmailAddress")</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit" onclick="return validate(this.form);" /></td>
</tr>
</table>
</div>
</div>
}
the source code of rendered by the page is :
<form action="/" method="post">
<div class="main-border" style="width: 890px;">
<div style="clear: both;">
</div>
<div style="padding: 0px 20px 0px 20px;">
<table style="width: 100%">
<tr>
<td colspan="2" class="main-subhead2">
<div class="label-text">
</div>
</td>
</tr>
<tr>
<td>Email :</td>
<td><Input class="text-box" data-val="True" data-val-regex-pattern="^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z]))*@[A-Za-z0-9_\.-]+[A-Za-z0-9_][A-Za-z0-9_]$" name="txtEmailAddress" type="Text" visible="True"></Input><span class="field-validation-valid" data-valmsg-for="txtEmailAddress" data-valmsg-replace="true"></span></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit" /></td>
</tr>
</table>
</div>
</div>
</form>
Input should be lowercased:
TagBuilder tagBuilder = new TagBuilder("input");
And don't forget to include the unobtrusive client side validation scripts to your page:
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
and ensure that client side validation is enabled in web.config:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>