Created by Manuel Lorenz
Last Updated on April 19, 2018

# What is Form Validation

Make sure to also watch the video on top of the page to see form validation in action!

Forms give the user the opportunity to enter data (name, address, email, etc) and to submit this data to a server - it’s as simple as that. In case this is totally new for you, make sure to check out this article to understand the form basics and that one to dive deeper into the logic behind forms and how data is sent to a server.

No matter which data we collect, we want to ensure that our users enter correct and complete information. Therefore validating forms is very helpful and exactly what we will work on in this article.

Specifically, we will use JavaScript to validate the information entered into the different fields of a form. Once each field contains valid information (and “valid” will be defined by us), the background color of a “Submit” button should change and this previously deactivated button should become clickable again to submit the data (we won’t implement a backup though). As a last step we’ll also prevent the default GET request which occurs after clicking the button.

The form is built in HTML and CSS (make sure to download the starting code), this is what it looks like:

form 4 # Working on the “Submit” Button We have three goals:

  • Change the button color when the form changes its validity
  • Make the button clickable
  • Prevent the default request

Let’s start with the color, which should change upon a certain condition. In our case we want to react to user input into one of our form fields. For that we need access to these form elements and we need to add a conditional statement to check whether all fields contain a specific user input/ value.

“Value” for the “Name” and “Your Message” fields should simply be any type of input, a single letter for example. For the “Mail” field validation, we will use a Regular Expression (RegEx). Make sure to check out this series in case you never worked with RegEx before.

So we need a conditional statement, in our example we will use if...else. But which code should be executed depending on which condition? We know that once all our conditions are met, the background color of our button should change (e.g. to #fa923f), otherwise it should keep the default color (#979695 in our case).

First we need to be able to select our button - let’s declare a variable for that:

var button = document.querySelector('.submit-button')

The corresponding if statement should be part of a function named checkInput.

This could be our starting code:

function checkInput() {
    if (...) {
        button.style.backgroundColor = '#fa923f';
    }
    else {
        button.style.backgroundColor = '#979695';
    }
}

Next we need access to our fields. As we already added IDs to these fields in our HTML code, we will use ID selectors for that purpose:

var inputName = document.getElementById('input-name')
var inputMail = document.getElementById('input-mail')
var inputMessage = document.getElementById('input-message')

By default all fields are empty, so our if condition simply should be fulfilled if this is not true any more (i.e. if all fields are not empty and therefore contain a value). As written above, we will use a more elaborate check for our mail though.

For the validity check of “Name” and “Message” we need access to the value property of our objects, the ability to check the current value of our objects and compare it with the value of the remaining objects.

Adding .value to our objects will give us access to the value property:

inputName.value
inputMessage.value

Now we have to find out if value is not equal to an empty value, a comparison operator will help us here:

inputName.value !== ''
inputMessage.value !== ''

As a last step, this should be true for all fields, so let’s add the code to our if condition. Additionally, adding the trim() method will remove any whitespace to the left and to the right of our string. This will ensure that our users enter actual values into the fields and not whitespaces only:

function checkInput() {
  if (inputName.value.trim() !== '' && inputMessage.value.trim() !== '') {
    button.style.backgroundColor = '#fa923f'
  } else {
    button.style.backgroundColor = '#979695'
  }
}

That’s already the entire code we need to validate our “Name” and “Message” fields, there is only one problem: When and how should checkInput be called?

# Using “oninput” to Call our Function

In the previous parts of this series we already worked with element.onclick and addEventListener to react to “click” events. This time we need a way to call our function whenever a value is entered into one of our fields.

We could also use the previously mentioned methods, but thankfully HTML also comes with an integrated event listener, which occurs whenever an element receives user input: oninput.

oninput is added as an attribute to the element itself. For this attribute we have to add a function, which should be executed whenever the event occurs - so each time the user enters a value into the field. Our previously defined checkInput function is the perfect solution for that, therefore we have to add oninput="checkInput()" to each of the input and the textarea elements.

Whenever the user now enters a value into one of the fields, our function will be called and check if all fields are no longer empty. If that’s the case, the background color of the button will change to #fa923f, in all other cases it will remain #979695.

Now we are able to validate the “Name” and “Message” fields, but what about the “Mail”?

Let’s first declare a variable containing a RegEx:

var regEx = /\S+@\S+\.\S+/

Using the standard RegEx syntax will allow us to test whether the value property of our inputMail object meets the RegEx pattern. If that’s the case our condition will be true, otherwise it will return false:

regEx.test(inputMail.value)

We have to add this code to our if statement though, which should look like this afterwards:

function checkInput() {
  if (
    inputName.value.trim() !== '' &&
    regEx.test(inputMail.value) &&
    inputMessage.value.trim() !== ''
  ) {
    button.style.backgroundColor = '#fa923f'
  } else {
    button.style.backgroundColor = '#979695'
  }
}

Our basic validation is now implemented, the button changes the color but it remains deactivated. Time to work on that.

# Activating the “Submit” Button

With the disabled attribute added (which is therefore automatically set to true) the button cannot be clicked. Changing this status from true to false ( = now we can click the button) is thankfully pretty easy with the code we created so far:

function checkInput() {
  if (
    inputName.value.trim() !== '' &&
    regEx.test(inputMail.value) &&
    inputMessage.value.trim() !== ''
  ) {
    button.style.backgroundColor = '#fa923f'
    button.disabled = false
  } else {
    button.style.backgroundColor = '#979695'
    button.disabled = true
  }
}

In case our inputs are valid, disabled will be set to false which allows us to click the button. For non valid inputs it remains true, so the button cannot be clicked. That was easy right?

# Preventing the Default Event

We almost finished our validation, but the default GET request which occurs whenever the submit event gets fired (you remember) should also be prevented.

For that we first need access to our form element:

var form = document.querySelector('.form')

We already learned how to use Event Listeners, let’s add such a listener to our form and listen to the submit event:

form.addEventListener('submit', function() {})

Whenever an event in JavaScript gets fired, a so-called default event object is created automatically. We can listen to this event by adding a parameter (with a name of your choice) to our function.

I will call it event and call the .preventDefault() method on it. This will prevent the default behaviour coming along with the submit event in a form, so sending a request (a GET request in our case) to the server.

Instead of this request, we will simply output “Submitted” to our console:

form.addEventListener('submit', function(event) {
  event.preventDefault()
  console.log('Submitted')
})

And that’s it, this was the last step of our validation!

This is just a simple example case how you could implement form validation with JavaScript. The main goal of this article was to get you more and more comfortable with the JavaScript syntax by applying it in a practical and (hopefully) easy to understand example.

See you in the other videos/ articles!