How to prevent form when clicking submit button and show error message on same page?

Hi how to prevent this form being submitted after clicking the submit button? I want the form to be stay on the page, and show the error once I leave it all blank, the code is working fine, but I need to click the signup button to show the form and error.

https://i.stack.imgur.com/H6C3x.gif

let registerBtn = document.querySelector("#RegisterBtn");
let signUp = document.querySelector("#signUp");

let modal = document.querySelector("#modal1");
modal.style.display = "none";

let closeBtn = document.querySelector(".close");
let overlay = document.querySelector("#overlay");
overlay.style.display = "none";

registerBtn.addEventListener("click", () => {
  modal.style.display = "block";
  overlay.style.display = "block";
  modal.classList.remove("hideModal");
});

closeBtn.addEventListener("click", () => {
  modal.classList.add("hideModal");
  overlay.style.display = "none";
});
**userController**
const User = require("../models/User");

exports.login = function (req, res) {
  let user = new User(req.body);
  user
    .login()
    .then(function (result) {
      req.session.user = { favColor: "blue", username: user.data.username };
      req.session.save(() => res.redirect("/"));
    })
    .catch(function (e) {
      req.flash("errors", e);
      req.session.save(() => res.redirect("/"));
    });
};

exports.logout = function (req, res) {
  req.session.destroy(function () {
    res.redirect("/");
  });
  // res.send("You are now logout");
};

exports.register = function (req, res) {
  let user = new User(req.body);
  user.register();
  if (user.errors.length) {
    user.errors.forEach((error) => {
      req.flash("regErrors", error);
    });
    req.session.save(() => {
      res.redirect("/");
    });
  } else {
    res.send("Congrats, there are no errors.");
  }
};

exports.home = function (req, res) {
  if (req.session.user) {
    res.render("home-dashboard", { username: req.session.user.username });
  } else {
    res.render("index-guest", { errors: req.flash("errors"), regErrors: req.flash("regErrors") });
  }
};
 <div id="modal1"
        class="absolute z-10 m-0 mr-20 transform -translate-x-1/2 -translate-y-1/2 top-1/2 left-1/2 animate-fadeIn">
        <span id="closeBtn" class="close" title="Close Modal">
            <i class="fas fa-window-close fa-2x" style="color: crimson; cursor: pointer;">
            </i>
        </span>
        <form method="POST" action="/register" id="registration-form"> 

            <div class="container flex flex-col p-20 bg-gray-200 rounded-xl">

               <%# Alert Message Error %>
          <% regErrors.forEach(function(message) { %>
                    <div class="max-w-md px-4 py-3 mx-auto leading-normal text-gray-100 transform bg-red-400 rounded-lg animate-fadeIn"  role="alert">
                <p class=""><%= message %></p>
            </div>
          <% }) %>
      
                <h1 class="mb-5 text-4xl font-medium text-gray-700">Sign Up</h1>
                <p class="mb-1">Please fill in this form to create an account.</p>
                <hr>

                <label class="mb-2 text-gray-700" for="userNameregister"><b>Username</b></label>
                <input name="username" class="p-3 mb-2 rounded-md " type="text" placeholder="Choose a username" 
                    id="userNameregister"  autocomplete="off">

                <label class="mb-2 text-gray-700" for="emailRegister"><b>Email</b></label>
                <input name="email" class="p-3 mb-2 rounded-md" type="text" placeholder="you@example.com"  id="emailRegister"
                     autocomplete="off">

                <label class="mb-2 text-gray-700" for="passwordRegister"><b>Password</b></label>
                <input name="password" class="p-3 mb-2 rounded-md" type="password" placeholder="Create a password" 
                    id="passwordRegister">

                <div>
                    <button  id="signUp" type="submit" 
                        class="p-3 mt-5 text-lg font-medium text-center bg-blue-600 rounded-lg cursor-pointer text-gray-50 delay-350 hover:bg-blue-800">Sign
                        Up</button>
                </div>
            </div>
        </form>
    </div>

You could attach an onSumit event listener to the form. Call e.preventDefault() and do your validation and then post it to your endpoint. You would also want to validate it on the backend

1 Like