JavaScript validation for empty input field

Javascript

Javascript Problem Overview


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?

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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

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

Example:

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

Solution 3 - Javascript

See the working example here

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

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>

Solution 4 - Javascript

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

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

It works on all modern browsers.

Solution 5 - Javascript

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

Solution 6 - Javascript

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 : https://stackoverflow.com/questions/608222/is-the-name-attribute-considered-outdated-for-a-anchor-tags

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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.

Solution 10 - Javascript

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

Solution 11 - Javascript

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

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

Solution 12 - Javascript

My solution below is in es6 because I made use of const if you prefer es5 you can replace all const with 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";
}

Solution 13 - Javascript

Combining all the approaches we can do something like this:

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

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.

Solution 14 - Javascript

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

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>

Solution 15 - Javascript

The following code worked for me perfectly:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEylaView Question on Stackoverflow
Solution 1 - JavascriptSk MouryaView Answer on Stackoverflow
Solution 2 - JavascriptRoko C. BuljanView Answer on Stackoverflow
Solution 3 - JavascriptSarfrazView Answer on Stackoverflow
Solution 4 - JavascriptAtif TariqView Answer on Stackoverflow
Solution 5 - JavascriptJak SamunView Answer on Stackoverflow
Solution 6 - JavascriptRajatView Answer on Stackoverflow
Solution 7 - JavascriptRizki FaujiView Answer on Stackoverflow
Solution 8 - JavascriptKenneth JView Answer on Stackoverflow
Solution 9 - JavascriptBalView Answer on Stackoverflow
Solution 10 - JavascriptKakizView Answer on Stackoverflow
Solution 11 - JavascriptRavindra BohraView Answer on Stackoverflow
Solution 12 - JavascriptKingston FortuneView Answer on Stackoverflow
Solution 13 - JavascriptA. MeshuView Answer on Stackoverflow
Solution 14 - JavascriptWemerson NinoView Answer on Stackoverflow
Solution 15 - JavascriptSpinstazView Answer on Stackoverflow