空の入力フィールドのJavaScript検証


95

<input name="question"/>送信ボタンをクリックして送信するときにIsEmpty関数を呼び出すこの入力フィールドがあり ます。

以下のコードを試してみましたが、うまくいきませんでした。何かアドバイス?

<html>

<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=unicode" />
  <meta content="CoffeeCup HTML Editor (www.coffeecup.com)" name="generator" />
</head>

<body>


  <script language="Javascript">
    function IsEmpty() {

      if (document.form.question.value == "") {
        alert("empty");
      }
      return;
    }
  </script>
  Question: <input name="question" /> <br/>

  <input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />

</body>

</html>


無効な回答を受け入れました。入力(またはtextarea)は常に文字列を返すため、nullのチェックは奇妙です。また、インラインJavaScriptは使用しないでください。また、盲目的に使用すべきではありませんreturn false...など
Roko C. Buljan '28

回答:


121

<script type="text/javascript">
  function validateForm() {
    var a = document.forms["Form"]["answer_a"].value;
    var b = document.forms["Form"]["answer_b"].value;
    var c = document.forms["Form"]["answer_c"].value;
    var d = document.forms["Form"]["answer_d"].value;
    if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
      alert("Please Fill All Required Field");
      return false;
    }
  }
</script>

<form method="post" name="Form" onsubmit="return validateForm()" action="">
  <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
  <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
  <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
  <textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>


2
'onsubmit = "return validate()"'を変更する必要があります。validateは関数の名前ではありません。'onsubmit = "return validateForm()"'である必要があります
tazboy

3
答えとOPの疑問を説明するのが最善です。
Vishal

7
これは実際には無効です。ifステートメント内のコンマにより、最後のチェックのみが返されます:stackoverflow.com/a/5348007/713874
Bing

35

こちらの実施例をご覧ください


必要な<form>要素がありません。コードは次のようになります。

function IsEmpty() {
  if (document.forms['frm'].question.value === "") {
    alert("empty");
    return false;
  }
  return true;
}
<form name="frm">
  Question: <input name="question" /> <br />
  <input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" />
</form>


フォームのすべてのフィールドに対してこれを行う方法はありますか?
14年

34

入力フィールドには空白を含めることができますが、これは避けたいです。String.prototype.trim()を
使用します。

function isEmpty(str) {
    return !str.trim().length;
}

例:

const isEmpty = str => !str.trim().length;

document.getElementById("name").addEventListener("input", function() {
  if( isEmpty(this.value) ) {
    console.log( "NAME is invalid (Empty)" )
  } else {
    console.log( `NAME value is: ${this.value}` );
  }
});
<input id="name" type="text">


1
nullと ""に加えて、このコードも欠けていました。それは私のために働いた。ロコに感謝します。
Pedro Sousa

17

ユーザーがJavaScriptを無効にした場合に必要な属性を追加したいと思います。

<input type="text" id="textbox" required/>

最新のすべてのブラウザで動作します。



7

入力要素にid "question"を追加して、これを試してください:

   if( document.getElementById('question').value === '' ){
      alert('empty');
    }

現在のコードが機能しない理由は、そこにFORMタグがないためです。また、「name」を使用した検索は非推奨であるためお勧めしません。

この投稿の@Paul Dixonの回答を参照してください:<name> 属性は<a>アンカータグに対して古くなっていますか?


1
if(document.getElementById("question").value == "")
{
    alert("empty")
}

1
... <input>要素に「id」属性はありません。IEが壊れているため、これはIEでのみ機能します。
先のとがっ

申し訳ありませんが、ID、document.getElementsByName( "question")[0] .value、または単に要素にIDを追加することを考えました
Kenneth J

1

入力要素にIDタグを追加するだけです...すなわち:

JavaScriptの要素の値を確認します。

document.getElementById( "question")。value

ああ、Firefox / Firebugを入手してください。これは、JavaScriptを実行する唯一の方法です。


0

以下の私のソリューションはconstes6にあります。es5を使用したい場合は、すべてconstをに置き換えることができるためvarです。

const str = "       Hello World!        ";
// const str = "                     ";

checkForWhiteSpaces(str);

function checkForWhiteSpaces(args) {
    const trimmedString = args.trim().length;
    console.log(checkStringLength(trimmedString))     
    return checkStringLength(trimmedString)        
}

// If the browser doesn't support the trim function
// you can make use of the regular expression below

checkForWhiteSpaces2(str);

function checkForWhiteSpaces2(args) {
    const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;
    console.log(checkStringLength(trimmedString))     
    return checkStringLength(trimmedString)
}

function checkStringLength(args) {
    return args > 0 ? "not empty" : "empty string";
}


0

<pre>
       <form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
           <input type="text"   id="name"   name="name" /> 
           <input type="submit"/>
       </form>
    </pre>

<script language="JavaScript" type="text/javascript">
  var frmvalidator = new Validator("myform");
  frmvalidator.EnableFocusOnError(false);
  frmvalidator.EnableMsgsTogether();
  frmvalidator.addValidation("name", "req", "Plese Enter Name");
</script>

上記のコードを使用する前に、gen_validatorv31.jsファイルを追加する必要があります


0

すべてのアプローチを組み合わせると、次のようなことができます。

const checkEmpty = document.querySelector('#checkIt');
checkEmpty.addEventListener('input', function () {
  if (checkEmpty.value && // if exist AND
    checkEmpty.value.length > 0 && // if value have one charecter at least
    checkEmpty.value.trim().length > 0 // if value is not just spaces
  ) 
  { console.log('value is:    '+checkEmpty.value);}
  else {console.log('No value'); 
  }
});
<input type="text" id="checkIt" required />

値を本当に確認したい場合は、サーバーで確認する必要がありますが、これはこの質問の範囲外です。


0

送信後に各入力をループして、それが空かどうかを確認できます

let form = document.getElementById('yourform');

form.addEventListener("submit", function(e){ // event into anonymous function
  let ver = true;
  e.preventDefault(); //Prevent submit event from refreshing the page

  e.target.forEach(input => { // input is just a variable name, e.target is the form element
     if(input.length < 1){ // here you're looping through each input of the form and checking its length
         ver = false;
     }
  });

  if(!ver){
      return false;
  }else{
     //continue what you were doing :)
  } 
})

0

<script type="text/javascript">
  function validateForm() {
    var a = document.forms["Form"]["answer_a"].value;
    var b = document.forms["Form"]["answer_b"].value;
    var c = document.forms["Form"]["answer_c"].value;
    var d = document.forms["Form"]["answer_d"].value;
    if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
      alert("Please Fill All Required Field");
      return false;
    }
  }
</script>

<form method="post" name="Form" onsubmit="return validateForm()" action="">
  <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
  <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
  <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
  <textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>


こんにちは。ソリューションを提供しているときに、将来の読者の役に立つ可能性のある問題をソリューションが解決する理由を提供してください。
Ehsan Mahmud
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.