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.
🌐
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 ...
Find elsewhere
🌐
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 ...
Top answer
1 of 1
3

See HTMLSelectElement.setCustomValidity()

The HTMLSelectElement.setCustomValidity() method sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does not have a custom validity error.

You're currently never resetting the custom validity message, so it remains 'Custom message: greater than 100 not allowed.' (or the other message for the other element) forever whenever an input is invalid. Insert else statements (if there is no rangeOverflow or no patternMismatch) that call setCustomValidity with the empty string to clear the error messages, in case any exist when the button is clicked:

const fp = document.getElementById('quantity');
const ide = document.getElementById('ide_pref');

fp.addEventListener('input', e => {
  if (fp.validity.rangeOverflow) {
    fp.setCustomValidity('Custom message: greater than 100 not allowed.');
  } else {
    fp.setCustomValidity('');
  }
});

ide.addEventListener('input', e => {
  if (ide.validity.patternMismatch) {
    ide.setCustomValidity('enter exactly webstorm OR vscode');
  } else {
    ide.setCustomValidity('');
  }
})
.u {
  margin-bottom: 15px;
}

.u:invalid {
  border: 2px solid orangered;
}

.u:valid {
  border: 2px solid greenyellow;
}

.btn {
  border: none;
  padding: 10px;
  border-radius: 8px;
  margin-top: 10px;
}

:focus {
  outline-color: gray;
}
<form action="#" method="get">
  <div>
    <label for="ide_pref">Would you prefer webstorm or vscode?</label>
    <input required class="u" type="text" pattern="webstorm|vscode" id="ide_pref" name="ide_pref"><br>
    <label for="quantity">How many licences would you like?</label>
    <input required class="u" type="number" min="1" max="100" id="quantity" name="lic_quantity"><br>
    <button class="btn" type="submit">Submit</button>
  </div>
</form>

🌐
Talkerscode
talkerscode.com › howto › javascript-form-validation-with-error-message.php
JavaScript Form Validation With Error Message
April 9, 2023 - 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.
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!

🌐
Linux Hint
linuxhint.com › javascript_form_validation
Javascript Form Validation
November 2, 2020 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
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
🌐
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.
🌐
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.
🌐
Adobe
helpx.adobe.com › coldfusion › developing-applications › requesting-and-presenting-information › validating-data-developing-guide › validating-form-input-and-handling-errors-with-javascript.html
Validating form input and handling errors with JavaScript
April 27, 2021 - If you use the onValidate attribute, you can also use the onError attribute to specify a JavaScript function that handles the validation errors. The following cfform tags support the onerror attribute: ... The error message text specified by the CFML tag's message attribute The following example ...
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript dom › javascript form validation
Master JavaScript Form Validation by Building a Form from Scratch
July 16, 2021 - ... You’ll use the <small> tag to show the error message to the users. If an input field isn’t valid, we’ll make its border color red by adding the error class to the form-field element.
🌐
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 ...