Create an HtmlHelper, which is a ValidatedTextBox. I did this using a reflection of my models, creating a fully dynamic jQuery integration with validation, but a simpler version will work like this (it will probably work, but not verified as it is). Good place to start:
public static MvcForm BeginClientValidatedForm(this HtmlHelper helper, string formId)
{
HttpResponseBase response = helper.ViewContext.HttpContext.Response;
if (helper.ViewData.ModelState.IsValid)
{
response.Write("<ul class=\"validation-summary-errors\"></ul>\n\n");
}
response.Write(ClientValidationHelper.GetFormValidationScript(formId));
response.Write("\n");
var builder = new TagBuilder("form");
builder.Attributes["id"] = formId;
builder.Attributes["name"] = formId;
builder.Attributes["action"] = helper.ViewContext.HttpContext.Request.Url.ToString();
builder.Attributes["method"] = HtmlHelper.GetFormMethodString(FormMethod.Post);
response.Write(builder.ToString(TagRenderMode.StartTag));
return new MvcForm(response);
}
And the corresponding "GetFormValidationScript":
public static string GetFormValidationScript(string formId)
{
string scriptBlock =
@"<script type=""text/javascript"">
$(document).ready(function() {{
$(""#{0}"").validate({{
meta:""rules"",
onkeyup:false,
onfocusout:false,
onclick:false,
errorClass:""input-validation-error"",
errorElement:""li"",
errorLabelContainer:""ul.validation-summary-errors"",
showErrors: function(errorMap, errorList) {{
$(""ul.validation-summary-errors"").html("""");
this.defaultShowErrors();
}}";
return string.Format(scriptBlock, formId);
}
public static string ClientValidatedTextbox(this HtmlHelper htmlHelper, string propertyName, IDictionary<string, object> htmlAttributes, string validationType)
{
var cssClassBuilder = new StringBuilder();
cssClassBuilder.Append("text ");
if (htmlAttributes == null)
{
htmlAttributes = new Dictionary<string, object>();
}
else if(htmlAttributes.ContainsKey("class"))
{
cssClassBuilder.Append(htmlAttributes["class"]);
}
switch validationType
{
case "email":
cssClassBuilder.Append(" {rules: {email: true, messages: {email: 'A valid email is required.'}} } ");
break;
}
htmlAttributes["class"] = cssClassBuilder.ToString();
return htmlHelper.TextBox(propertyName, htmlAttributes);
}
source
share