1

潜在顧客向けの情報フィールドを含むフォームがあります。スパマーは、アドレス フィールドに Web アドレスを入力しています。フィールドに「http://」が含まれている場合にエラー メッセージを表示したい

フォームコードは次のとおりです。

<label>First Name:</label> <input id="first_name" name="first_name" type="text" size="20" />
<label>Last Name:</label> <input id="last_name" name="last_name" type="text" size="20" />
<label>Address:</label> <input name="address" type="text" size="30" />
<label>City, State &nbsp;Zip:</label> <input name="city" type="text" size="20" value="City, State Zip"/>
<label>Phone Number:</label> <input name="phone" type="text" size="20" />
<label>Email:</label> <input id="email" name="email" type="text" size="30" />

これが私が持っているエラーコードです:

    function validateForm(){
    message = '';
    error = 0;

    if (document.contact_form.first_name.value == '') { 
        message = 'First name is a required field\n'; 
        error = 1;
    }
    if (document.contact_form.last_name.value == '') { 
        message = message + 'Last name is a required field\n'; 
        error = 1;
    }
    if (document.contact_form.phone.value == '') { 
        message = message + 'Phone Number is a required field\n'; 
        error = 1;
    }
    if (document.contact_form.email.value == '') { 
        message = message + 'Email is a required field\n'; 
        error = 1;
    }   
    if (WHAT GOES HERE TO SHOW THAT THE FIELD CAN'T CONTAIN ANY VARIATION OF 'http://?') { 
        message = message + 'That is not a valid address\n'; 
        error = 1;
    }


    if (error) {
        alert(message);
        return false;
    } else {
        return true;
    }
}
4

3 に答える 3

0

正規表現を使用します。

if (/^http:\/\//.test(document.contact_form.email.value)) {
    message = message + 'That is not a valid address\n'; 
    error = 1;
}

文字列の先頭でのみhttp://をテストすることを想定しています(文字^列のどこかでテストする場合は削除してください)。

于 2012-08-11T03:33:23.210 に答える
0

indexOf以下の機能を使用できます。

if(document.contact_form.address.value.indexOf("http://") !== -1) {
    message = message + "That is not a valid address\n"; 
    error = true;
}

indexOf-1関数パラメータで指定された値indexOfが文字列に見つからない場合に返されます。

参照:

于 2012-08-11T03:36:23.830 に答える
-1

問題の入力にクラスを与えてください。おそらく、私が行ったこと以外のものです。ID にわかりやすい名前を付けます。

コーディングがずっと簡単になります。

function validate() {

                    var inputs = document.querySelectorAll('.inputs'),
                        i = 0;
                    for (; i < inputs.length; i++) {
                        if (inputs[i].value == '') {
                            message = message + ' ' + inputs[i].id + ' is a required field\n';
                        };
                    };
                };
于 2012-08-11T03:47:21.883 に答える