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

Uncategorized

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">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"
    />
    <link
      rel="stylesheet"
      href="style.css
"
    />
    <title>Document</title>
  </head>
  <body>
    <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
    </h4>
    <form action="#">
      <input type="text" name="text" placeholder="Input integer" />
      <input type="submit" class="btn" name="submit" />
    </form>
    <script src="main.js"></script>
  </body>
</html>
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) {
  e.preventDefault();

  console.log(typeof input.value);

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

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

Leave a Reply

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