15

ボタンのクリック時にフォームの検証を処理しようとしています。フォームを検証していますが、エラーは表示されていません。誰でもこれで私を助けることができますか?

<form id="the-form" action="#">
    <input type="text" required="required" placeholder="Required text" />
    <input type="email" required="required" placeholder="email" />
    <button id="btn" type="button">Submit</button>
</form>

JavaScript:

$("#btn").on("click", function(){
    if($("#the-form")[0].checkValidity())
    {
        alert('validated');
    }
    else
    {
        //show errors
        return false;
    }
});

http://jsfiddle.net/5ycZz/

4

5 に答える 5

32

試す

reportValidity()

だからあなたは持っているでしょう

$("#btn").on("click", function(){
    if($("#the-form")[0].checkValidity()) {
        alert('validated');
    }
    else {
        $("#the-form")[0].reportValidity();
    }
});
于 2017-07-19T20:50:39.250 に答える
5

以下の手順を実行してこれを達成しました。

1)私はフォームを持っています:

<form>
    <textarea required></textarea>
    <input type="submit" style="display:none;"/>
</form>

<a>Some other button to trigger event</a>

2) 次に、フォームが正しく入力されているかどうかを確認する必要があります。

//this is <a> click event:
if (!$('form')[0].checkValidity()) {
    $('form').find('input[type="submit"]').click();
    return false;
}

これによりフォーム送信がトリガーされますが、エラーがあるため送信されません;)

input[type="submit"] クリック時に html5 検証エラーが表示されるようです:)

あなたにもうまくいくことを願っています!:)

于 2014-07-31T07:52:02.603 に答える
4

ここに完璧な答えがあります

<form id="the-form" action="#">
<input type="text" required="required" placeholder="Required text" />
<input type="email" required="required" placeholder="email" />
<button id="btn" type="submit">Submit</button>

$("#btn").on("click", function(){
if($("#the-form")[0].checkValidity())
{
    alert('validated');
}
else
{
  return 0;
}

});

于 2014-12-09T07:28:56.073 に答える
0

else ステートメントを削除します。(アップデート)

$("#btn").on("click", function(){
if($("#the-form")[0].checkValidity())
{
    alert('validated'); //will appear if name and email are of valid formats
}
});
于 2013-09-05T10:50:00.563 に答える