空输入字段的 JavaScript 验证

Posted

技术标签:

【中文标题】空输入字段的 JavaScript 验证【英文标题】:JavaScript validation for empty input field 【发布时间】:2011-04-25 15:35:24 【问题描述】:

我有这个输入字段 <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>

【问题讨论】:

您接受的答案无效。检查 null 很奇怪,因为输入(或 textarea)总是返回一个字符串。此外,您不应该使用内联 JavaScript。另外你不应该盲目使用return false...等等等等 【参考方案1】:

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

【讨论】:

'onsubmit="return validate()"' 需要更改。 validate 不是函数的名称。应该是'onsubmit="return validateForm()"' 最好解释一下答案和OP的疑问。 这个接受实际上是无效的。 if 语句中的逗号将导致仅返回最后一个检查:***.com/a/5348007/713874【参考方案2】:

输入字段可以有空格,我们希望防止这种情况发生。 使用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` );
  
);
&lt;input id="name" type="text"&gt;

【讨论】:

除了 null 和 "",我的代码我也错过了这部分。它对我有用。谢谢罗科。【参考方案3】:

See the working example here


您缺少必需的&lt;form&gt; 元素。你的代码应该是这样的:

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>

【讨论】:

有没有办法对表单中的所有字段执行此操作?【参考方案4】:

如果用户禁用 javascript,我想添加必需的属性:

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

它适用于所有现代浏览器。

【讨论】:

【参考方案5】:
if(document.getElementById("question").value.length == 0)

    alert("empty")

【讨论】:

【参考方案6】:

在您的输入元素中添加一个 id “问题”,然后试试这个:

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

您当前的代码不起作用的原因是您没有 FORM 标记。此外,不推荐使用“名称”进行查找,因为它已弃用。

在这篇文章中查看@Paul Dixon 的答案:Is the 'name' attribute considered outdated for <a> anchor tags?

【讨论】:

【参考方案7】:

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

【讨论】:

您好,当您提供解决方案时,最好提供您的解决方案解决问题的原因,这可能对未来的读者有所帮助。【参考方案8】:
if(document.getElementById("question").value == "")

    alert("empty")

【讨论】:

...&lt;input&gt; 元素上没有“id”属性;这仅适用于 IE,因为 IE 已损坏。 对不起,我以为有ID,document.getElementsByName("question")[0].value,或者只是给元素添加一个ID【参考方案9】:

只需在输入元素中添加一个 ID 标记...即:

并检查 javascript 中元素的值:

document.getElementById("question").value

哦,是的,获取 firefox/firebug。这是执行 javascript 的唯一方法。

【讨论】:

【参考方案10】:

您可以在提交后循环遍历每个输入并检查它是否为空

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 :)
   
)

【讨论】:

【参考方案11】:

我下面的解决方案是在 es6 中,因为我使用了 const,如果您更喜欢 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";

【讨论】:

【参考方案12】:

<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 文件

【讨论】:

【参考方案13】:

结合所有方法,我们可以做这样的事情:

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'); 
  
);
&lt;input type="text" id="checkIt" required /&gt;

请注意,如果您真的想检查值,您应该在服务器上执行此操作,但这超出了本问题的范围。

【讨论】:

【参考方案14】:

点击 Javascript 按钮时使用 HTML 验证自定义输入消息

function msgAlert() 
  const nameUser = document.querySelector('#nameUser');
  const passUser = document.querySelector('#passUser');

  if (nameUser.value === '')
    console.log('Input name empty!');
    nameUser.setCustomValidity('Insert a name!');
   else 
    nameUser.setCustomValidity('');
    console.log('Input name ' + nameUser.value);
  


const v = document.querySelector('.btn-petroleo');
v.addEventListener('click', msgAlert, false);
.containerdisplay:flex;max-width:960px;
.w-auto 
    width: auto!important;

.p-3 
    padding: 1rem!important;

.align-items-center 
    -ms-flex-align: center!important;
    align-items: center!important;

.form-row 
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -5px;
    margin-left: -5px;

.mb-2, .my-2 
    margin-bottom: .5rem!important;

.d-flex 
    display: -ms-flexbox!important;
    display: flex!important;

.d-inline-block 
    display: inline-block!important;

.col 
    -ms-flex-preferred-size: 0;
    flex-basis: 0;
    -ms-flex-positive: 1;
    flex-grow: 1;
    max-width: 100%;

.mr-sm-2, .mx-sm-2 
    margin-right: .5rem!important;

label 
    font-family: "Oswald", sans-serif;
    font-size: 12px;
    color: #007081;
    font-weight: 400;
    letter-spacing: 1px;
    text-transform: uppercase;

label 
    display: inline-block;
    margin-bottom: .5rem;

.x-input 
    background-color: #eaf3f8;
    font-family: "Montserrat", sans-serif;
    font-size: 14px;

.login-input 
    border: none !important;
    width: 100%;

.p-4 
    padding: 1.5rem!important;

.form-control 
    display: block;
    width: 100%;
    height: calc(1.5em + .75rem + 2px);
    padding: .375rem .75rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;

button, input 
    overflow: visible;
    margin: 0;

.form-row 
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -5px;
    margin-left: -5px;

.form-row>.col, .form-row>[class*=col-] 
    padding-right: 5px;
    padding-left: 5px;

.col-lg-12 
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
    max-width: 100%;

.mt-1, .my-1 
    margin-top: .25rem!important;

.mt-2, .my-2 
    margin-top: .5rem!important;

.mb-2, .my-2 
    margin-bottom: .5rem!important;

.btn:not(:disabled):not(.disabled) 
    cursor: pointer;

.btn-petroleo 
    background-color: #007081;
    color: white;
    font-family: "Oswald", sans-serif;
    font-size: 12px;
    text-transform: uppercase;
    padding: 8px 30px;
    letter-spacing: 2px;

.btn-xg 
    padding: 20px 100px;
    width: 100%;
    display: block;

.btn 
    display: inline-block;
    font-weight: 400;
    color: #212529;
    text-align: center;
    vertical-align: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-color: transparent;
    border: 1px solid transparent;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    border-radius: .25rem;
    transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;

input 
    -webkit-writing-mode: horizontal-tb !important;
    text-rendering: auto;
    color: -internal-light-dark(black, white);
    letter-spacing: normal;
    word-spacing: normal;
    text-transform: none;
    text-indent: 0px;
    text-shadow: none;
    display: inline-block;
    text-align: start;
    appearance: textfield;
    background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59));
    -webkit-rtl-ordering: logical;
    cursor: text;
    margin: 0em;
    font: 400 13.3333px Arial;
    padding: 1px 2px;
    border-width: 2px;
    border-style: inset;
    border-color: -internal-light-dark(rgb(118, 118, 118), rgb(195, 195, 195));
    border-image: initial;
<div class="container">
              <form name="myFormLogin" class="w-auto p-3 mw-10">
                <div class="form-row align-items-center">
                  <div class="col w-auto p-3 h-auto d-inline-block my-2">
                    <label class="mr-sm-2" for="nameUser">Usuário</label><br>
                    <input type="text" class="form-control mr-sm-2 x-input login-input p-4" id="nameUser"
                           name="nameUser" placeholder="Name" required>
                  </div>
                </div>
                <div class="form-row align-items-center">
                  <div class="col w-auto p-3 h-auto d-inline-block my-2">
                    <label class="mr-sm-2" for="passUser">Senha</label><br>
                    <input type="password" class="form-control mb-3 mr-sm-2 x-input login-input p-4" id="passUser"
                           name="passUser" placeholder="Password" required>
                    <div class="help">Esqueci meu usuário ou senha</div>
                  </div>
                </div>
                <div class="form-row d-flex align-items-center">
                  <div class="col-lg-12 my-1 mt-2 mb-2">
                    <button type="submit" value="Submit" class="btn btn-petroleo btn-lg btn-xg btn-block p-4">Entrar</button>
                  </div>
                </div>
                <div class="form-row align-items-center d-flex">
                  <div class="col-lg-12 my-1">
                    <div class="nova-conta">Ainda não é cadastrado? <a href="">Crie seu acesso</a></div>
                  </div>
                </div>
              </form>
            </div>

【讨论】:

【参考方案15】:

以下代码非常适合我:

<form action = "dashboard.php" onsubmit= "return someJsFunction()">
  <button type="submit" class="button"  id = "submit" name="submit" >Upload to live listing</button>
</form>
    <script type="text/javascript">

       function someJsFunction()

        const input = document.getElementById('input1');

        if(input.value === "")
          alert ("no input?"); // This will prevent the Form from submitting
          return false;                              
        else
          return true; // this will submit the form and handle the control to php.
        
     

</script>

【讨论】:

以上是关于空输入字段的 JavaScript 验证的主要内容,如果未能解决你的问题,请参考以下文章

Java Script学习 6(转)

如果字段为空需要另一个字段,Laravel 验证规则

如果空值传递给Django中的表单字段,如何验证表单?

JSR 303 验证,如果一个字段等于“某物”,则这些其他字段不应为空

JS表单验证

javascript AlphaNum输入字段验证