2

JS ファイルをリンクして入力を検証することにより、ユーザーの入力を検証しようとしています。ただし、間違ったデータで送信ボタンをクリックすると、フォームが送信され、検証エラーは発生しません。

フォーム:

<form id="user_form" name="contactForm" action="#" method="GET" onsubmit="return validateForm();">

<p id="first_name" class="input_title">First name <span class="asterisk_red">*</span></p>

<!-- The HTML 5 'Required' attribute will not allow the form to be sent empty. -->
<input class="input_box" type="text" name="first_name" placeholder="Joe" />

<input id="submit_button" type="submit" name="submit" value="Submit"/>

</form>

そして、検証に使用する JS:

function validateForm(){

/* Validate the first name field of the form */
var fn = document.forms['contactForm'].first_name.value;

/* If the Name string is empty then return false and show warning. */
if (fn == ""){
    alert("First name must be filled out");
    document.forms['contactForm'].first_name.reset();
    return false;
}else if(fn.length <= 2){
    alert("Your first name must more than two characters");
    document.forms['contactForm'].first_name.reset();
    return false;
}


}
4

3 に答える 3

1

要素でreset()を呼び出すことができるかどうかはわかりません。フォームオブジェクトでそのメソッドを使用して、すべてのフィールドをクリアすると思います。IEとFFには問題がないようですが、Chromeには問題があるようです。その結果、chromeはjavascriptを実行せず、常にフォームを送信します。これがフィドルフォーム送信と更新されたコードです:

function validateForm() {

            /* Validate the first name field of the form */
            var fn = document.forms['contactForm'].first_name.value.trim();

            /* If the Name string is empty then return false and show warning. */
            if (fn == "") {
                alert("First name must be filled out");
                document.forms['contactForm'].first_name.value = '';//Removed reset
                return false;
            } else if (fn.length <= 2) {
                alert("Your first name must more than two characters");
                document.forms['contactForm'].first_name.value = '';//Removed reset
                return false;
            }
            return true;//Added
        }
于 2013-02-02T19:06:58.777 に答える
0

この結果を確認してください: Form Validation jsFiddle より多くの入力と GET を使用したフォーム検証があります。

また、 jQuery Validationを構築する方法については、Jquery リファレンスも参照してください。

または、プラグインの検証を使用します。

<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

$(document).ready(function(){
    $("#commentForm").validate();
  });
于 2013-02-02T18:46:06.117 に答える
-1

フォームで通常のボタンを使用し、javascript 関数を使用してフォームを送信できます。

于 2013-02-02T18:45:50.320 に答える