Validating ASP.NET MVC Client using jQuery using Html.ValidationMessage?

I am trying to connect to an HTML.ValidationMessage () element to write client-side validation in fact using jQuery. Is it possible? My server side validation is displayed using HTML.ValidationMessage (), and I am wondering how I can access this element to display a custom message using jQuery before submitting the form.

I know that there are several plugins to do some of these things, but I would really like my control to go through full control.

Here is some Javascript code that I have. It basically adds a โ€œclassโ€ check to the input element to send, but is not sure how to access Html.ValidationMessage to print something like โ€œEmail requiredโ€.

    <script type="text/javascript">
    $(document).ready(function() {
        $("input[type=submit]").click(function() {

            var valid = true;

            // email blank
            if ($("input[name='email']").val().length < 1) {
                $("input[name='email']").addClass("input-validation-error");
                valid = false;
            }

            return valid;
        })
    });

</script>

And the code from the view:

       <p>
            <label for="email">
                Email:</label>
            <%= Html.TextBox("email") %>
            <%= Html.ValidationMessage("email") %>
        </p>
+5
source share
4 answers

. xVal, , . .NET, aspx, jQuery. , , , .

.

+8

jquery ? . javascript , . , , " ", .

+2

"none", .

    <p>
        <label for="email">
            Email:</label>
        <%= Html.TextBox("email") %><span style="display:none" class="email-error">Email required</span>
        <%= Html.ValidationMessage("email") %>
    </p>

JS :

        if ($("input[name='email']").val().length < 1) {
            $("input[name='email']").addClass("input-validation-error");
            valid = false;
        }

:

        if ($("input[name='email']").val().length < 1) {
            $("input[name='email']").addClass("input-validation-error");
            $("span.email-error").show();
            valid = false;
        }

CSS , , .

EDIT:

:

$("span.email-error").show();

:

$("input[name='email']").after('<span style="display:none" class="email-error">Email required</span>');
+1

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");

    // Inject the standard form into the httpResponse.
    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();
      }}";

      // etc...this is the standard jQuery.validate code.

      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);
}
0
source

All Articles