Validate Calculator Inputs Using JavaScript and Regular Expressions

The calculator is often seen as one of the more trivial, beginner friendly applications to build. Today we will walk through how we can validate inputs being passed to the calculator to ensure we have a valid mathematical equation.

Matthew Bub
The Startup
5 min readJan 17, 2021

--

Photo by Karolina Grabowska from Pexels

Getting Started

If you are here to follow along, you can grab a copy of the starter code here. which includes the HTML, CSS and JavaScript I will be referring to through out.

Build the calculator buttons

Let’s begin by creating the calculator’s buttons. We could hard code our buttons using HTML, however I would rather use vanilla JavaScript to avoid writing repetitious code.

First let’s loop through the array containing the button values. Within our loop, we can create a new button and append it to the DOM.

We’ve created a function that builds the buttons for the calculator

Let’s recap what we’ve just done. We started by creating a for loop within our handleBuild function. Then, with proper semantics in mind, we have added several methods within our for loop before setting the buttons inner text and then finally, we append the individual button to the DOM until the for loop has a current index that matches the length of the array.

Using Chrome Dev Tools to inspect the local .html file

As it stands now, we can click our buttons but nothing will happen. This is because we haven’t told the buttons to do anything. Let’s change that!

Assign the on click event

The purpose of the on click events should be to pass each value accordingly. There are several scenarios we will need to consider, more on that in a moment.

Assigned the onclick event

We’ve intentionally set up the on click event at a very basic level, let’s validate this works by refreshing our page and then clicking our buttons with the Developer Tools open. We should see the individual characters printing to our console now.

Once we’ve confirmed the characters are printing to the console, we can move forward with printing the respective character to the DOM. Let’s refactor the onclick event by assigning it it’s own function. We will declare this one outside of our handleBuild function.

Added on click event that prints content to the DOM

Now let’s get back to the conditions, or scenarios I mentioned above. When we break down the core purpose of a calculator, we realize the intention of a click event attached to each button should execute its own traditional operation. Simple enough, however there are a few conditions that will need to be met before we have a valid mathematical equation.

  • The first input entered must be a positive or negative integer
  • Operators must follow integers
  • = should calculate the total
  • c should clear the result printed to the screen

Introduction to Regular Expressions

If you are not familiar with Regular Expression, they are a sequence of characters used to define a search pattern. You may have seen them in the wild, and if completely unfamiliar, it was likely the least sensible line of code you saw aside from a binary file.

For example, a regular expression used to find a date might look like this: /(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g

Personally, I have found regex101.com to be a great service for validating and testing regular expressions on the fly. They also have a great feature to explain and break down what each individual character is doing.

Using RegEx to validate calculator inputs

It’s worth noting this is not the only way to build a calculator.

This is a great situation to get familiar with Regular Expressions, let’s walk through each condition we mentioned above one by one.

Clear results

Starting with the easiest condition first, let’s use RegEx to find the c input and clear the text on screen.

Using a Ternary Operator and RegEx, we should be able to successfully clear content on the DOM. A bug we will encounter here is the c still prints to the DOM. That’s okay for now.

Allow negative numbers

The next one will be a bit more involved, we will need to check against 2 conditions to allow negative numbers. My first approach was to build a string that checks for an optional - and a number of any range. E.g./^\-?\d+/

This works for its sole purpose but becomes flawed quickly when trying to move past the first number, as everything will return true following the first match. Not the end of the world however more involved than I was looking for. We will need to break this down further, let’s focus on just the sign. If the operator is the first character in the string, we can allow it. We can check for numbers in a separate condition.

Cool, we are off to an awesome start here. Now we can allow numbers to print as well!

Notice how we’ve got everything already hooked up to automatic handle this condition. Go ahead and test it out! We should be able to enter positive/negative numbers of any size into our calculator and clear our input. We should not be able to add an operator following the number yet.

Use RegEx to find operators

We need to make sure the operator isn’t the first character entered. We also need to make sure the last character in our validated string was a number.

At this point, we should be able to recursively create any mathematical expression with the operators we’ve allowed. All that is left is to calculate the total.

Calculating the total

Now what we are about to do next is opinionated, you might challenge yourself to find an alternative to my quick solution.

There are some things to take into consideration when using eval() and I would generally advise you not to use it on anything other than exactly what we are doing here.

We should now have a fully functioning calculator. If you’ve found this article useful, I would love to hear about it. 👏

View the full source file below.

--

--