2009-05-08 11 views
2

私は職場でフォーム検証スクリプトを作成していますが、問題があります。このフォームは、ユーザーが名前、実際の電子メール、カテゴリ(ドロップダウンから)、質問を記入することを保証するためのものです。インラインJavaScriptフォームの検証

これはフォームに名前を付け、フォームからすべてのデータを収集します:

<script> 

    function checkForm(form1) { 
name = document.getElementById("FieldData0").value; 
category = document.getElementById("FieldData3").value; 
question = document.getElementById("FieldData1").value; 
email = document.getElementById("FieldData2").value; 

これは何かが「名前」フィールドにあることを確認するためにチェックします。正常に動作し、エラーテキストを表示するように正確に検証します。

if (name == "") { 
    hideAllErrors(); 
document.getElementById("nameError").style.display = "inline"; 
document.getElementById("FieldData0").select(); 
document.getElementById("FieldData0").focus(); 
    return false; 

これはまさにこれと同じように動作します。これは、電子メールのフィールドが空であるかどうかをチェックし、それが空の場合、エラーテキストを表示し、そのフィールドを選択します。

} else if (email == "") { 
hideAllErrors(); 
document.getElementById("emailError").style.display = "inline"; 
document.getElementById("FieldData2").select(); 
document.getElementById("FieldData2").focus(); 
    return false; 
    } 

これはまた、それは、質問フィールドが空でないことを確認する必要があるだけのように動作します:

else if (question == "") { 
hideAllErrors(); 
document.getElementById("questionError").style.display = "inline"; 
document.getElementById("FieldData1").select(); 
document.getElementById("FieldData1").focus(); 
    return false; 
    } 

この1つは、部分的に動作します - フォームを提出しながら、ダウン何のドロップが選択されていない場合は、エラーメッセージが表示されますが、それは提出からフォームを停止しない、それだけでエラーテキストが表示されます。

else if (category == "") { 
hideAllErrors(); 
document.getElementById("categoryError").style.display = "inline"; 
document.getElementById("FieldData3").select(); 
document.getElementById("FieldData3").focus(); 
    return false; 
    } 

私はどこに置いても、これはまったく動作しません。私は先週同じスクリプトでバリエーションを使用しましたが、うまくいきました。ユーザーが砲撃されていないので、この機能はすべてのエラーを隠し

function check_email(e) { 
ok = "1234567890qwertyuiop[][email protected]_QWERTYUIOPASDFGHJKLZXCVBNM"; 

for(i=0; i < e.length ;i++){ 
if(ok.indexOf(e.charAt(i))<0){ 
return (false); 
} 
} 

if (document.images) { 
re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/; 
re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; 
if (!e.match(re) && e.match(re_two)) { 
return (-1);   
} 

} 

} 

:これは、電子メールをチェックアウトし

else if (!check_email(document.getElementById("FieldData1").value)) { 
hideAllErrors(); 
document.getElementById("emailError2").style.display = "inline"; 
document.getElementById("FieldData2").select(); 
document.getElementById("FieldData2").focus(); 
    return false; 
    } 

Otherwise it lets the form submit: 


    return true; 
    } 

:これは、電子メールは、実際の電子メールアドレスのようなルックスに入ったことを確認してくださいすることになっています赤いテキストで。私は "のdocument.getElementById(" emailError ")に入れてみましたがどれも "" それが全部壊れないstyle.displayを=。":

function hideAllErrors() { 
document.getElementById("nameError").style.display = "none" 
document.getElementById("emailError").style.display = "none" 
document.getElementById("categoryError").style.display = "none" 
document.getElementById("questionError").style.display = "none" 

    } 


</script> 

を、フォームは次のようになります。

<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1"> 

<p><div class=error id=nameError>Required: Please enter your name<br/></div><p><strong>Name:</strong> <span></span><br><input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" /> 
<label for="name"></label></p> 

<p><div class=error id=emailError>Required: Please enter your email address<br/></div> 
<div class=error id=nameError2>This doesn't look like a real email address, please check and reenter<br/></div> 
<strong><p>Email:</strong> <span>(will not be published)</span><br><input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" /> 
<label for="email"></label> 
</p> 

<div class=error id=categoryError>Please select a category from the drop-down menu<br></div> 
<p><strong>Category:</strong> <span></span><br> 
<p><select id="FieldData3" name="FieldData3"> 
<option value="">Please select a category</option> 
<option value="a">a</option> 
<option value="b">b</option> 
<option value="c">c</option> 
<option value="d">d</option> 
<option value="e">e</option> 
<option value="f">f</option> 
<option value="other">Other</option> 
</select><label for="category"></label> 

<p><div class=error id=questionError>Please type your question in the box below:<br></div><label for="question"><strong><p>Your Question:</strong> <span></span></label><br> 

<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea></p> 

<p><input type="submit" class="btn" value="Submit Question" name="Submit"></p> 
</div> 
</form> 

小切手を発行する順序は問題ですか?私はこれを理解できないようです。どんな助けもありがとう。

答えて

5

私は、より読みやすく、デバッグしやすくするために、JavaScriptを書き直す自由を取ってきました。

Marc Bernierが述べたように、dropdown要素はselect関数をサポートしていないので、例外を防ぐためにifステートメントをその周りに置いています。私もあなたのcheckEmail機能を簡略化しましたが、むしろ複雑なようでした。 checkFormコードを簡単にするために、名前をisAnInvalidEmailに変更しました。

あなたのHTMLに 'emailError2' divという名前が間違って付けられていると、JavaScriptで別の例外が発生します。あなたのHTMLは面倒で、場合によっては無効です。一部の属性値と欠落している終了タグに引用符がありません。 W3C validatorを使用して、HTMLがきれいで規格に準拠していることを確認する必要があります。私はjsbinにあなたのコードを主催してきました

:(http://jsbin.com/iyeco/edit経由で編集可能)http://jsbin.com/iyeco

はここでクリーンアップのJavascriptです:

function checkForm() { 
    hideAllErrors(); 
    var formIsValid = 
    showErrorAndFocusIf('FieldData0', isEmpty, 'nameError') 
    && showErrorAndFocusIf('FieldData2', isEmpty, 'emailError') 
    && showErrorAndFocusIf('FieldData2', isAnInvalidEmail, 'emailError2') 
    && showErrorAndFocusIf('FieldData3', isEmpty, 'categoryError') 
    && showErrorAndFocusIf('FieldData1', isEmpty, 'questionError'); 

    /* For debugging, lets prevent the form from submitting. */ 
    if (formIsValid) { 
    alert("Valid form!"); 
    return false; 
    } 

    return formIsValid; 
} 

function showErrorAndFocusIf(fieldId, predicate, errorId) { 
    var field = document.getElementById(fieldId); 
    if (predicate(field)) { 
    document.getElementById(errorId).style.display = 'inline'; 
    if (field.select) { 
     field.select(); 
    } 
    field.focus(); 
    return false; 
    } 

    return true; 
} 

function isEmpty(field) { 
    return field.value == ''; 
} 

function isAnInvalidEmail(field) { 
    var email = field.value; 

    var ok = "1234567890qwertyuiop[][email protected]_QWERTYUIOPASDFGHJKLZXCVBNM"; 

    for(i = 0; i < email.length; i++){ 
    if(ok.indexOf(email.charAt(i)) < 0) { 
     return true; 
    } 
    } 

    re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/; 
    re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; 
    return re.test(email) || !re_two.test(email); 
} 



function hideAllErrors() { 
    document.getElementById("nameError").style.display = "none" 
    document.getElementById("emailError").style.display = "none" 
    document.getElementById("emailError2").style.display = "none" 
    document.getElementById("categoryError").style.display = "none" 
    document.getElementById("questionError").style.display = "none" 
} 

そしてクリーンアップHTML:

<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1"> 
    <div> 
    <div class="error" id="nameError"> 
     Required: Please enter your name 
    </div> 
    <label for="FieldData0"><strong>Name:</strong></label> 
    <input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" /> 
    </div> 

    <div> 
    <div class="error" id="emailError"> 
     Required: Please enter your email address 
    </div> 
    <div class="error" id="emailError2"> 
     This doesn't look like a real email address, please check and reenter 
    </div> 
    <label for="FieldData2"><strong>Email:</strong>(will not be published)</label> 
    <input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" /> 
    </div> 

    <div> 
    <div class="error" id="categoryError"> 
     Please select a category from the drop-down menu 
    </div> 
    <label for="FieldData3"><strong>Category:</strong></label> 
    <select id="FieldData3" name="FieldData3"> 
     <option value="">Please select a category</option> 
     <option value="a">a</option> 
     <option value="b">b</option> 
     <option value="c">c</option> 
     <option value="d">d</option> 
     <option value="e">e</option> 
     <option value="f">f</option> 
     <option value="other">Other</option> 
    </select> 
    </div> 

    <div> 
    <div class="error" id="questionError"> 
     Please type your question in the box below: 
    </div> 
    <label for="FieldData1"><strong>Your Question:</strong></label> 
    <textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea> 
    </div> 

    <input type="submit" class="btn" value="Submit Question" name="Submit"> 
</form> 
+0

このような徹底的な答えをありがとうございます。私はあなたのアドバイスを心に刻みます。 –

+0

大歓迎です。ハッピーコーディング! – brianpeiris

0

最初の問題は:そこから行く...機能にそのif文の内容を移動します。基本的に同じことをしているコードが5つほどあります。

次へ:あなたはそれを保持するだけのものを移動するための汎用的なdiv要素を作成し、一度に一つのエラーメッセージを許可しているからです。こうすることで、あなたは

続いなど、他人を表示する、特定のエラーを隠すを追跡する必要はありませんだけ...あなたのcheck_email関数からtrueまたはfalseを返す-1を返すと偽、などが悪い形でありますたとえjavascriptがそのようなことに寛大であっても。

あなたのコードをクリーンアップしたら、それはデバッグに非常に容易になります。

0

は、私は他のチェーン場合、全体を取り払うことをお勧めしますし、個別にこの本にそれぞれをチェックします。

var error = 0; 
if (value == '') { 
    error = 1; 
    // other stuff; 
} 

if (value2 == '') { 
    error = 1; 
    // do stuff; 
} 

... 

if (error) { 
    // show error 
} else { 
    // submit form 
} 
+0

なぜエラー= 1 | 0?これまで真実を聞いたことはありますか? – roryf

+0

これは現在のコードよりはるかに優れているわけではありませんが、依然として多くの重複があります。 – brianpeiris

+0

それは私が思っていたことです、それは別の半ダースの6のように思えます。しかし、助けてくれてありがとう。 –

0

==キャストを入力していない===のために交換してみてください。それはドロップダウンの問題であなたを助けるかもしれません。

関数がfalseを返していて、-1も返される可能性があります。

私はJavaScriptを!-1で何種類キャスト分からないとして、あなたはまた、この実行する必要があります、ドロップダウン上のエラーについて

!check_email(...) 
1

check_email(...)!==false; 

これに代えをこの行を呼び出さないでください:

document.getElementById( "FieldData1")。select();

私は数週間前にまったく同じ問題を抱えているように思います。

+0

あなたは正しいですが、ドロップダウンのIDは "FieldData3"です。 – brianpeiris

+0

ええ、私はそれを普通のテキストフィールドのように扱おうとしていました。私の間違い。 –

関連する問題