空输入字段的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>


您接受了无效的答案。由于输入(或文本区域)始终返回String,因此检查null是奇怪的。另外,您不应使用内联JavaScript。你也不要盲目使用return false......等等等等
ROKO C. Buljan

Answers:


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 2014年

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>


有没有办法对表单中的所有字段执行此操作?
备胎

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和“”外,我的代码也缺少这部分。它为我工作。谢谢Roko。
Pedro Sousa 2015年



7

将id“问题”添加到您的输入元素,然后尝试以下操作:

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

您当前的代码不起作用的原因是因为您那里没有FORM标签。另外,不建议使用“名称”查找,因为它已被弃用。

请参阅此帖子中的@Paul Dixon的答案:对于<a>锚标记,'name'属性是否已过时?


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

我下面的解决方案是在es6中,因为我利用了const如果您更喜欢es5,则可以全部替换constvar

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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.