電子書籍の厳選無料作品が豊富!

送信フォームの入力内容チェックについて 送信フォーム作成の勉強をしています。
「必須項目未記入」と「半角英数以外の文字入力」を同時にチェックする方法をお聞きしたいです。

「必須項目未記入」と「半角英数以外の文字入力」の時に赤字で警告を表示させたいです。
「必須項目未記入」は赤字で警告が表示されるのですが、「半角英数以外の文字入力」の時は赤字で警告が表示されません。。。



素人で説明不足かもしれませんが、助言をいただきたいです。
よろしくお願いいたします。

(URL↓)
http://www.photoiku.com/sample/form-sample.php



(Javascript↓)
<script type="text/javascript">
<!--
function formCheck(){
var flag = 0;

if( document . Form1 . InputText1 . value . match ( /[^0-9a-zA-Z_]+/ ) ){
flag = 1;
document . getElementById( 'notice-input-text-1' ) . style . display = "block";
}else{
document . getElementById( 'notice-input-text-1' ) . style . display = "none";
}


if( document . Form1 . InputText1 . value == "" ){
flag = 1;
document . getElementById( 'notice-input-text-1' ) . style . display = "block";
}else{
document . getElementById( 'notice-input-text-1' ) . style . display = "none";
}



if( document . Form1 . Textarea1 . value == "" ){
flag = 1;
document . getElementById( 'notice-textarea-1' ) . style . display = "block";
}else{
document . getElementById( 'notice-textarea-1' ) . style . display = "none";
}
if( flag ){
window . alert( '入力内容に不備があります。' );
return false;
}else{
return true;
}
}
// -->
</script>



(html↓)
<form name="Form1" method="post" action="#" onsubmit="return formCheck()">
<p>ID(必須)(半角英数)</p>
<p id="notice-input-text-1" style="display: none; color: red;"> 【半角英数で入力されているか確認して下さい】</p>
<p><input type="text" name="InputText1"></p>
<p>コメント(必須)</p>
<p id="notice-textarea-1" style="display: none; color: red;"> 【コメントを入力して下さい】</p>
<p><textarea name="Textarea1" rows="5" cols="40"></textarea></p>
<p><input type="submit" value="送信"></p>
</form>

補足ですが、1つ目のif~elseのブロックと、2つ目のif~elseのブロックを入れ替えてもできませんでした。

A 回答 (1件)

InputText1に「あいうえお」という文字列が入っていたとしましょう。


このときのformCheckをトレースしてみます。


function formCheck(){
 var flag = 0;

 if( document . Form1 . InputText1 . value . match ( /[^0-9a-zA-Z_]+/ ) ){
  //**半角英数以外の文字が入っているのでこちらへ**
  flag = 1;
  document . getElementById( 'notice-input-text-1' ) . style . display = "block"; //警告表示
 }else{
  document . getElementById( 'notice-input-text-1' ) . style . display = "none";
 }

 if( document . Form1 . InputText1 . value == "" ){
  flag = 1;
  document . getElementById( 'notice-input-text-1' ) . style . display = "block";
 }else{
  //**InputText1は空ではないのでこちらへ**
  document . getElementById( 'notice-input-text-1' ) . style . display = "none"; //せっかく表示した警告を非表示に……
 }

(略)
}

1つの入力項目に複数のチェックをかける場合、
「エラーがあった時点でその入力項目はそれ以上調べない」ようにすると
このようなミスを防ぐことができます。
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!