You need to stop the submission if an error occured:

HTML

<form name ="myform" onsubmit="return validation();"> 

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}
Answer from Zoltan Toth on Stack Overflow
🌐
W3Schools
w3schools.com › js › js_validation.asp
JavaScript Form Validation
HTML form validation can be done by JavaScript. If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn_web_development › Extensions › Forms › Form_validation
Client-side form validation - Learn web development | MDN
When this attribute is set, the element matches the :required UI pseudo-class and the form won't submit, displaying an error message on submission, if the input is empty. While empty, the input will also be considered invalid, matching the :invalid UI pseudo-class. If any radio button in a same-named group has the required attribute, one of the radio buttons in that group must be checked for the group to be valid; the checked radio doesn't have to be the one with the attribute set.
🌐
W3Resource
w3resource.com › javascript-exercises › event › javascript-event-handling-exercise-4.php
JavaScript form validation - Display error for empty fields
Learn how to implement form validation in JavaScript to display an error message when required fields are left empty upon form submission. Enhance your web development skills with this interactive JavaScript program.
🌐
Javascript-coder
javascript-coder.com › html-form › form-validation
JavaScript Form Validation Script: More features | JavaScript Coder
Create a place to display the error message next to the input elements For example place a DIV next to the input element and have it ID of the format: {formname}{inputname}errorloc Example: <div id='myform_Name_errorloc' ></div> <input type="text" name="Name" /> ... Sometimes it may be required ...
🌐
W3C
w3.org › WAI › WCAG21 › Techniques › client-side-script › SCR32
SCR32: Providing client-side validation and adding error text via the DOM | WAI | W3C
Enter an invalid value in the field(s) associated with an error message and verify that the correct error message for the field is displayed. ... Enter a valid value in the field(s) associated with the displayed error message and verify that the error message is removed.
🌐
Linux Hint
linuxhint.com › javascript_form_validation
Javascript Form Validation
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
DEV Community
dev.to › tracy4code › form-validation-with-javascript-21l6
Form Validation with JavaScript - DEV Community
June 3, 2023 - The code listens for the form submission event and prevents the form from submitting by default. It then performs validations on each input field and displays appropriate error messages in the errorMessage divs and applies the success and error classes to the parent formDetails divs based on the validation result.
Find elsewhere
🌐
Tutorial Republic
tutorialrepublic.com › javascript-tutorial › javascript-form-validation.php
JavaScript Form Validation - Tutorial Republic
Client-side validation is also ... occurs within the user's web browser, whereas server-side validation occurs on the server, which require user's input to be first submitted and sent to the server before validation occurs, also user has to wait for server response to know what exactly went wrong. In the following section we will take a closer look at how to perform JavaScript form validation and handle any input errors found ...
🌐
Talkerscode
talkerscode.com › howto › javascript-form-validation-with-error-message.php
JavaScript Form Validation With Error Message
After this let us see our JavaScript function that is written inside script tag and comes into response when we trying to submit our form. Here, as you see we apply our basic validations in which if any thing remains empty at the time of submission of form and password is less than 8 characters than it will focus that thing and shows an alert message related to error.
🌐
The Art of Web
the-art-of-web.com › javascript › validate
Form Validation < JavaScript
The regular expression ^[\w ]+$ ... error message when the input is blank. The purpose of a form validation script is to return a boolean value (true or false) to the onsubmit event handler. A value of true means that form will be submitted while a false value will block the form from being ...
🌐
Hyva
docs.hyva.io › hyva-themes › writing-code › form-validation › javascript-form-validation.html
JavaScript form validation - Hyvä Docs
The form submission is prevented by the onSubmit function until either all validation rules pass or the one of the fields has an invalid value. For fields with async validators, error messages will be displayed as soon as all field rules have completed.
🌐
Siteglide
docs.siteglide.com › en › cms › forms › go-further-forms › custom-javascript-validation-for-forms
Forms Error Callback and Validation | Siteglide Docs
function error(error) { //Format the error message error = s_error_formatter(error); //Select the key DOM elements var standard_errors = document.querySelectorAll(".input-error:not([data-custom-msg])"); var custom_errors = document.querySelectorAll(".input-error[data-custom-msg]"); var old_errors = document.querySelectorAll(".my-input-error"); var standard_error_message = "<div class=\"my-input-error alert alert-warning\">This field is required.</div>"; //Delete old error messages for (e=0;e<old_errors.length;e++) { old_errors[e].parentNode.removeChild(old_errors[e]); } //Add standard field va
🌐
Medium
medium.com › stackanatomy › form-validation-using-javascripts-constraint-validation-api-fd4b70720288
Form Validation Using JavaScript’s Constraint Validation API | by Craig Buckler | StackAnatomy | Medium
January 11, 2022 - Attempting to submit an empty, invalid, or out-of-range value stops form submission and shows a generic error message: You can stop the browser’s default validation by adding: ... :focusthe field with focus :focus-withinan element contains a field with focus :focus-visiblean element has focus owing to keyboard navigation :requireda field with a required attribute :optionala field without a required attribute :valida field that has passed validation :invalida field that has not passed validation :user-valida field that has passed validation after a user interaction (Firefox only) :user-invali
Top answer
1 of 2
1

There are plenty of form validation tutorials out there to give you further inspiration.

This version makes use of data attributes and is very scalable without the need for more javascript. More work will be needed for additional input types but should be enough to get you started.

//Set valudation on blur for each of the elements
document.querySelectorAll("[data-customvalidate] input").forEach(function(element) {
  element.addEventListener("blur", function() {
    validateField(this)
  });
});


//Set form validation
document.querySelectorAll("[data-customvalidate").forEach(function(element) {
  element.addEventListener("submit", function(event) {
    let isNotValid = false;
    //Go through each of the input element
    this.querySelectorAll("input").forEach(function(input) {
      //Validate the input and set the isNotValid flg
      if (validateField(input) && !isNotValid) {
        isNotValid = true;
      }
    });

    //Stop the form submit if not valid
    if (isNotValid) {    
      event.preventDefault();
    }
  });
});


//Main Validation Funtion
function validateField(field) {
  let attributes = field.getAttributeNames();
  let parent = field.parentNode
  let errorField = parent.querySelector(".formError");

  let isError = false;
  //Required Vlidation
  if (attributes.includes("required") && field.value === "") {
    errorField.textContent = `The ${field.dataset.errorfieldname} field is required`;
    isError = true;
    //Min Length Validation
  } else if (attributes.includes("minlength") && (field.value.length < field.getAttribute("minlength"))) {
    errorField.textContent = `The mininmum length for ${field.dataset.errorfieldname} field is ${field.getAttribute("minlength")} characters`;
    isError = true;
    //Match Validation
  } else if (attributes.includes("data-mustmatch")) {
    let elementToMatch = document.getElementById(field.dataset.mustmatch);
    if (elementToMatch.value !== field.value) {
      errorField.textContent = `The ${elementToMatch.dataset.errorfieldname} and ${field.dataset.errorfieldname} do not match`;
      isError = true;
    }
  }

  parent.classList.toggle("error", isError);
  return isError;
}
label {
  display: block;
}

label:not(.error)>.formError {
  display: none;
}

label>.formError {
  color: red;
  font-weight: bold;
  padding-left: 1em;
}
<form novalidate data-customvalidate>
  <label for="password">
         <input type="password" name="password" id="password" placeholder="Password*" required minlength="8" data-errorfieldname="Password" />
         <span class="formError"></span>
      </label>
  <label for="confirmpassword">
        <input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" data-errorfieldname="Confirm Password" data-mustmatch="password" data-mustmatcherror= "Password and Confirm Password do not match" />
        <span class="formError"></span>
      </label>
  <button>Submit</button>
</form>

2 of 2
0

Just try this one! In here, the form won't be submitted if the password or confirm password is missing or the confirm password is not same as the first password.

function empty() {
    if (document.getElementById("password").value == "") {
        document.getElementById("pwmessage").innerHTML = "Enter at least one character to the password field";
        return false;
    }
    if (document.getElementById("confirm_password").value != document.getElementById("password").value) {
        document.getElementById("cpwmessage").innerHTML = "Please check your password and try again";
        return false;
    };
}
<form novalidate action='process.php' method='get'>
    <label for="password">
       <input type="password" name="password" id="password" placeholder="Password*" required minlength="8" /><br>
       <span id='pwmessage'></span><br>
    </label>
    <label for="confirmpassword">
      <input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" /><br>
      <span id='cpwmessage'></span><br>
    </label>
    <input type="submit" value="submit" onClick="return empty()" />
</form>

Thanks and best regards!

🌐
Bootstrap
getbootstrap.com › docs › 5.0 › forms › validation
Validation · Bootstrap v5.0
We recommend using client-side validation, but in case you require server-side validation, you can indicate invalid and valid form fields with .is-invalid and .is-valid. Note that .invalid-feedback is also supported with these classes. For invalid fields, ensure that the invalid feedback/error message is associated with the relevant form field using aria-describedby (noting that this attribute allows more than one id to be referenced, in case the field already points to additional form text).
🌐
Advancedbytez
advancedbytez.com › generate-accessible-form-error-messages-using-javascript
How to Generate Accessible Form Error Messages Using JavaScript - Advancedbytez
February 6, 2024 - Validates Username and Password by checking if they’re empty, if they are it generates an error message and sets the aria-invalid attribute to “true” indicating to screen readers that the input field needs attention.
🌐
freeCodeCamp
freecodecamp.org › news › form-validation-with-html5-and-javascript
Data Validation – How to Check User Input on HTML Forms with Example JavaScript Code
January 18, 2021 - This will help you define the user experience of the validation - whether to show an error message inline or at the top of the form, how detailed should the error message be, should the form be sumitted anyways, should there be analytics to track invalid format of data? And so on. You can perform JavaScript ...