空输入字段的JavaScript验证

时间:2010-10-14 20:57:35

标签: javascript

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

14 个答案:

答案 0 :(得分:97)

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

答案 1 :(得分:33)

See the working example here


您缺少必需的<form>元素。以下是您的代码应该如何:

function IsEmpty(){
  if(document.forms['frm'].question.value === "")
  {
    alert("empty");
    return false;
  }
    return true;
}

<强> HTML:

<form name="frm">
  Question: <input name="question"/> <br />
  <input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question"/>
</form>

答案 2 :(得分:26)

输入字段可以有空格,您要阻止它:

function isEmpty(str){
    return !str.replace(/\s+/, '').length;
}

示例:

function isEmpty(str){
    return !str.replace(/\s+/, '').length;
}

document.getElementById("name").addEventListener("input", function() {
  if( isEmpty(this.value) ) {
     console.log( "NAME IS EMPTY!" )
  }
});
<input id="name" type="text">

答案 3 :(得分:15)

我想在用户禁用javascript时添加必需的属性:

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

适用于所有现代浏览器。

答案 4 :(得分:8)

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

答案 5 :(得分:5)

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

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

您当前代码无效的原因是因为您没有FORM标记。此外,建议不要使用“name”进行查找,因为它已弃用。

请参阅@Paul Dixon在这篇文章中的回答:Is the 'name' attribute considered outdated for <a> anchor tags?

答案 6 :(得分:1)

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

答案 7 :(得分:1)

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

并检查javascript中的元素值:

的document.getElementById( “问题”)。值

哦,你得到firefox / firebug。这是做javascript的唯一方法。

答案 8 :(得分: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 文件

答案 9 :(得分:0)

我下面的解决方案是在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";
}

答案 10 :(得分: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 />

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

答案 11 :(得分: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 :)
  } 
})

答案 12 :(得分: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>

答案 13 :(得分:0)

点击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);
.container{display: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>