JavaScript form validation with promises and exceptions handling

It is good to know the basics of handling web forms. The client entered data usually requires initial validation handled by the JavaScript interpreter of the browser. Here is how to approach the aspects of validating and sending data, as well as parsing the returned server response with the help of JavaScript built-in features such as promises and exceptions. More on them you can learn in this JavaScript course.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <style>
    #info {
      opacity: 1;
      transition: opacity 5s;
    }

    #info.hidden {
      opacity: 0;
    }
  </style>
</head>

<body>

  <form id="user-input">
    <div class="form-control">
      <label for="username">Username</label>
      <input type="text" id="username" />
    </div>
    <div class="form-control">
      <label for="password">Password</label>
      <input type="password" id="password" />
    </div>
    <button type="submit" id="submit" disabled>Create User</button>
  </form>

  <span id="info"></span>


<script>
  const REQUIRED = 'REQUIRED';
  const MIN_LENGTH = 'MIN_LENGTH';

  function isValid(value, attr, validatorValue) {
    if (attr === REQUIRED) { return value.trim().length > 0; }
    if (attr === MIN_LENGTH) { return value.trim().length > validatorValue; }
  }

  function createUser(userName, userPassword) {
    if (!isValid(userName, REQUIRED) || !isValid(userPassword, MIN_LENGTH, 5)) {
      throw new Error('Wrong username or password.'); // client-side check
    }
    // return the server-side check promise
    return new Promise(function (resolve, reject) {
      // db checking logic
      is_created = true;
      if (is_created) {
        resolve(
          {
            userName: userName,
            createdAt: +new Date,
            message: 'successfully created user'
          }
        )
      }
      else {
        reject(
          {
            message: 'not valid user or password'
          }
        );
      }
    });
  }

  function displayInfo(info) {
    const info_el = document.querySelector('#info');
    info_el.innerHTML = JSON.stringify(info);
    info_el.classList.toggle('hidden');
  }

  function signupHandler(event) {
    event.preventDefault();
    try {
      createUser(enteredUsername.value, enteredPassword.value)
        .then( // return from the server-side promise
          (info) => { displayInfo(info); },
          (error) => { displayInfo(error); }
        );
    } catch (err) { displayInfo(err.message); } // return from client-side error (throw)
    // .message is auto generated from the throw error object
  }

  const form = document.querySelector('#user-input');
  form.addEventListener('submit', signupHandler);

  // access the form controls
  const submitBtn = form.querySelector('#submit');
  const enteredPassword = form.querySelector('#password');

  const enteredUsername = form.querySelector('#username');
  enteredUsername.addEventListener('input', () => {
    // this.value points to window object, because => preserve the parent context
    submitBtn.disabled = !isValid(enteredUsername.value, REQUIRED);
  });

</script>

</body>
</html>

Congratulations and enjoy learning JavaScript!
Author Photo

About Nevyan Neykov

I do web design and development for more than 15 years. Have been working in various companies dealing mainly with PHP and JavaScript. Independently as well as in teams, I am involved in design and development of user friendly websites. Exploring the new aspects of JavaScript language such as ES6, as well as the Angular framework and how to apply them in practice. Nowadays I find dealing with Docker / Kubernetes and Linux system administration compelling. @youtube: https://www.youtube.com/channel/UC69XQPDbEpfAtO5S2-ZyNoA at udemy: https://www.udemy.com/user/nevyan-neykov/ Have a nice day !

View Full Profile →