JavaScript validation for empty input field

by Eyla   Last Updated July 12, 2019 05:26 AM

Greeting, 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>
Tags : javascript


Answers 10


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>

Sarfraz
Sarfraz
October 14, 2010 21:02 PM

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?

Rajat
Rajat
October 14, 2010 21:04 PM

if(document.getElementById("question").value == "")
{
    alert("empty")
}
Kenneth J
Kenneth J
October 14, 2010 21:04 PM

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.

Bal
Bal
October 14, 2010 21:05 PM

if(document.getElementById("question").value.length == 0)
{
    alert("empty")
}
Jak Samun
Jak Samun
June 15, 2013 21:21 PM

<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>
Sk Mourya
Sk Mourya
January 09, 2014 10:40 AM

An input field can have whitespaces, you want to prevent that:

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

Example:

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

Roko C. Buljan
Roko C. Buljan
February 12, 2015 19:10 PM

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

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

It works on all modern browsers.

Atif Tariq
Atif Tariq
August 10, 2016 11:08 AM

<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

Ravindra Bohra
Ravindra Bohra
November 17, 2017 11:03 AM

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

Kingston Fortune
Kingston Fortune
April 03, 2019 16:44 PM

Related Questions


Updated March 15, 2017 04:26 AM

Updated May 20, 2017 20:26 PM

Updated February 05, 2018 07:26 AM

Updated October 25, 2017 02:26 AM

Updated August 02, 2018 02:26 AM