Check Empty String with JavaScript

Web Design & Web Development

Demo

Sponsored links

 

Code

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Check Empty String with JavaScript</title>
    <link rel="stylesheet" type="text/css" href="https://demo.plantpot.works/assets/css/normalize.css">
    <link rel="stylesheet" href="https://use.typekit.net/opg3wle.css">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="validation.js"></script>
  </head>
  <body>
    <div id="container">
      <form id="form" class="form" name="form" action="#" method="post">
        <div class="form-input-box">
          <input id="form-input" class="form-input" type="text" name="text" placeholder="Enter text" oninput="checkString()">
          <p id="msg" class="msg"></p>
        </div>
      </form>
    </div>
  </body>
</html>

CSS

@charset "utf-8";
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html {
  font-size: 16px;
}
body {
  background-color: #f5f6e7;
  font-family: futura-pt, sans-serif;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}
#container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 100%;
  height: 100vh;
}
.form {
  width: 100%;
  max-width: 450px;
  padding: 20px;
}
.form-input-box {
  position: relative;
}
.form-input {
  width: 100%;
  padding: 15px 10px;
  border: 1px solid #3d3935;
  border-radius: 4px;
  background-color: #fff;
  color: #3d3935;
  font-size: 1.125rem;
  outline: 0;
}
.form-input::placeholder {
  color: #ccc;
  font-size: 1.125rem;
}
.msg {
  position: absolute;
  bottom: -30px;
  left: 0;
  font-size: 1.125rem;
}
.invalid .msg {
  color: #bf0404;
}
.valid .form-input {
  border: 1px solid #23b08d;
  background-image: url("valid.svg");
  background-position: 98%;
  background-size: 20px 20px;
  background-repeat: no-repeat;
}
.invalid .form-input {
  border: 1px solid #bf0404;
  background-image: url("invalid.svg");
  background-position: 98%;
  background-size: 20px 20px;
  background-repeat: no-repeat;
}

JavaScript

function checkString() {
  var form = document.getElementById("form");
  var str = document.getElementById("form-input").value;
  var msg = document.getElementById("msg");

  if(str === "") {
    form.classList.remove("valid");
    form.classList.add("invalid");
    msg.innerHTML = "This field is required.";
  }
  else {
    form.classList.remove("invalid");
    form.classList.add("valid");
    msg.innerHTML = "";
  }
}