jQueryを使ってASP.NET MVCのクライアント検証Html.ValidationMessageを使用していますか?

StackOverflow https://stackoverflow.com/questions/661798

質問

私はjQueryを使ってこれは本当にカスタムクライアント側の検証を書くことHTML.ValidationMessage()要素を活用しようとしています。これさえ可能ですか?私のサーバー側の検証がHTML.ValidationMessage()を使用して表示されている、と私は私が提出フォームの前にjQueryを使ってカスタムメッセージを表示するには、その要素にアクセスする方法を疑問に思ってます。

私はこのようなもののいくつかを行うにはそこにいくつかのプラグインがあるけど、私は本当に私の検証との完全な制御をしたいと思います。

ここで私は、現在持っているJavaScriptコードのビットです。基本的にはしかし、提出上の入力要素に同様の出力何かにHtml.ValidationMessageにアクセスする方法がわから検証「クラス」ではない追加「メールが必要。」

    <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>

そして、コードビューから:

       <p>
            <label for="email">
                Email:</label>
            <%= Html.TextBox("email") %>
            <%= Html.ValidationMessage("email") %>
        </p>
役に立ちましたか?

解決

これを行うには、コードのトンを書くことができます。それとも、ただ無料で、ない、まさにこの、プラスはるかれ、 XVAL して使用することができます。あなたの.NETの型に入れて値の注釈は、あなたのASPXに、単純な物事のカップルを追加し、あなたは自由のためのjQueryの検証を取得します。それに加えて人気のあるフレームワークのプロバイダが付属しており、それはあなたがより複雑な検証が必要な場合には非常にカスタマイズ可能です。

私はここで車輪の再発明する必要を見ない。

他のヒント

それだけで検証プラグインクライアント側のために?これは、ビューのコードで実装するのは簡単です。あなたは、入力ボックスにいくつかのタグを追加し、ヘッダにはJavaScriptの数行を追加すれば完了です。勿論あなたはまだ、いわば「非常にカスタム」だ何かをコーディングする必要があると思います。

ページに静的にメッセージを入れて、それが「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>');

ValidatedTextBoxあるのHtmlHelperを作成します。私は検証して完全に動的なjQueryの統合を作成し、私のモデルでの反射を利用して、これをやったが、簡単なバージョンが(これはおそらく動作しますが、そのままでテストされます)このように動作します。開始するには良い場所:

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

とそれに対応する "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);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top