Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript validation for empty input field

Tags:

javascript

People also ask

How check input field is empty in jQuery?

To check if the input text box is empty using jQuery, you can use the . val() method. It returns the value of a form element and undefined on an empty collection.

How do you add a validation to the input field?

To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form.


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

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

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>

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

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

It works on all modern browsers.