[javascript] JavaScript validation for empty input field

I have this input field <input name="question"/> I want to call IsEmpty function when submit clicking submit button.

I tried the code below but did not work. any advice?

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title></title>_x000D_
  <meta http-equiv="Content-Type" content="text/html; charset=unicode" />_x000D_
  <meta content="CoffeeCup HTML Editor (www.coffeecup.com)" name="generator" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
  <script language="Javascript">_x000D_
    function IsEmpty() {_x000D_
_x000D_
      if (document.form.question.value == "") {_x000D_
        alert("empty");_x000D_
      }_x000D_
      return;_x000D_
    }_x000D_
  </script>_x000D_
  Question: <input name="question" /> <br/>_x000D_
_x000D_
  <input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

This question is related to javascript

The answer is


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

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  function validateForm() {_x000D_
    var a = document.forms["Form"]["answer_a"].value;_x000D_
    var b = document.forms["Form"]["answer_b"].value;_x000D_
    var c = document.forms["Form"]["answer_c"].value;_x000D_
    var d = document.forms["Form"]["answer_d"].value;_x000D_
    if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
      alert("Please Fill All Required Field");_x000D_
      return false;_x000D_
    }_x000D_
  }_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
  <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
_x000D_
_x000D_


You can loop through each input after submiting and check if it's empty

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

Customizing the input message using HTML validation when clicking on Javascript button

_x000D_
_x000D_
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);
_x000D_
.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;
}
_x000D_
<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>
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
<pre>_x000D_
       <form name="myform" action="saveNew" method="post" enctype="multipart/form-data">_x000D_
           <input type="text"   id="name"   name="name" /> _x000D_
           <input type="submit"/>_x000D_
       </form>_x000D_
    </pre>_x000D_
_x000D_
<script language="JavaScript" type="text/javascript">_x000D_
  var frmvalidator = new Validator("myform");_x000D_
  frmvalidator.EnableFocusOnError(false);_x000D_
  frmvalidator.EnableMsgsTogether();_x000D_
  frmvalidator.addValidation("name", "req", "Plese Enter Name");_x000D_
</script>
_x000D_
_x000D_
_x000D_

before using above code you have to add the gen_validatorv31.js file


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

Just add an ID tag to the input element... ie:

and check the value of the element in you javascript:

document.getElementById("question").value

Oh ya, get get firefox/firebug. It's the only way to do javascript.


Combining all the approaches we can do something like this:

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

Note that if you truly want to check values you should do that on the server, but this is out of the scope for this question.


See the working example here


You are missing the required <form> element. Here is how your code should be like:

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


An input field can have whitespaces, we want to prevent that.
Use String.prototype.trim():

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

Example:

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


Add an id "question" to your input element and then try this:

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

The reason your current code doesn't work is because you don't have a FORM tag in there. Also, lookup using "name" is not recommended as its deprecated.

See @Paul Dixon's answer in this post : Is the 'name' attribute considered outdated for <a> anchor tags?


I would like to add required attribute in case user disabled javascript:

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

It works on all modern browsers.


My solution below is in es6 because I made use of const if you prefer es5 you can replace all const with var.

_x000D_
_x000D_
const str = "       Hello World!        ";_x000D_
// const str = "                     ";_x000D_
_x000D_
checkForWhiteSpaces(str);_x000D_
_x000D_
function checkForWhiteSpaces(args) {_x000D_
    const trimmedString = args.trim().length;_x000D_
    console.log(checkStringLength(trimmedString))     _x000D_
    return checkStringLength(trimmedString)        _x000D_
}_x000D_
_x000D_
// If the browser doesn't support the trim function_x000D_
// you can make use of the regular expression below_x000D_
_x000D_
checkForWhiteSpaces2(str);_x000D_
_x000D_
function checkForWhiteSpaces2(args) {_x000D_
    const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;_x000D_
    console.log(checkStringLength(trimmedString))     _x000D_
    return checkStringLength(trimmedString)_x000D_
}_x000D_
_x000D_
function checkStringLength(args) {_x000D_
    return args > 0 ? "not empty" : "empty string";_x000D_
}
_x000D_
_x000D_
_x000D_