JavaScript Form validation using Regular Expression, validate only numbers with optional plus minus sing


In this tutorial we are goin to validate a HTML Form using JavaScript Regular Expressions or also known as RegEx, and we are going to specifically look for the type of input of numbers only and with an optional plus (+) or minus sing (-) from our user.

If you wish to se the video version please flow the YouTube link below:

Source Code for the javascript tutorial :

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <h1 class="title">Form Validation</h1>
    <h2 class="title">Validate all numbers plus(+) or minus(-)</h2>
    <h4 class="title">
      Input integer with an optional leading plus(+) or minus(-) sign
    <form action="#">
      <input type="text" name="text" placeholder="Input integer" />
      <input type="submit" class="btn" name="submit" />
    <script src="main.js"></script>
body {
  max-width: 700px;
  margin: auto;
  line-height: 2;
  background-color: #333;
  color: #ddd;
form {
  width: 300px;
  margin: auto;

.title {
  text-align: center;
  margin-bottom: 2rem;
  text-shadow: 2px 2px 3px black;
h1.title {
  text-transform: uppercase;
h2.title {
  color: #26a69a;
input[type="text"] {
  color: #26a69a;
  font-size: 2rem;
input[type="text"]::placeholder {
  color: gray;
.btn {
  width: 100%;
const input = document.querySelector('input[type="text"]');

const submitBtn = document.querySelector('input[type="submit"]');

console.log(input, submitBtn);

submitBtn.addEventListener("click", allNumbersPlusMinus);

function allNumbersPlusMinus(e) {

  console.log(typeof input.value);

  let numbers = /^[-+]?[0-9]+$/;

  if (input.value.match(numbers)) {
    submitBtn.value = "Match";
    input.value = "";
  } else {
    alert("No Match!");
    submitBtn.value = "Try again";

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.