1

I am trying to add some error messages to my inputs through JS, but I am not exactly sure how I should go about this, and everything I've tried does not function well.

I am trying to display an error, and prevent the form from submitting, if there is an error.

<form novalidate>
      <label for="password">
         <input type="password" name="password" id="password" placeholder="Password*" required minlength="8" />
         <span id='pwmessage'></span>
      </label>
      <label for="confirmpassword">
        <input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" />
        <span id='cpwmessage'></span>
      </label>
      <button>Submit</button>
  </form>
  • where is `check()` function? – s.kuznetsov Apr 18 '22 at 21:29
  • Sorry. It was remnant of something I was trying. I edited it out. – bigorangeduck Apr 18 '22 at 21:32
  • maybe you can show us what you were trying to do?! and we'll just recoded it, rather than developing the functionality all over again. – s.kuznetsov Apr 18 '22 at 21:35
  • 1
    You can use the [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output) tag. – Zakk Apr 18 '22 at 21:35
  • Can you please explain in which case the error message should appear? I mean something like when the password's length is below 12, when the password doesn't contain capital letter or something. – Vishal Kalansooriya Apr 18 '22 at 22:00
  • @VishalKalansooriya When the password field is empty, for example. – bigorangeduck Apr 18 '22 at 22:03
  • I have added an answer which works according to your needs. (Empty password) Is that all you need :) – Vishal Kalansooriya Apr 18 '22 at 22:27
  • @bigorangeduck why are you using `novalidate` ? – Zakk Apr 18 '22 at 22:38
  • 1
    You should include what you tried at least. There are many ways to do this, in fact you should check both front and backend to be sure. There are many online examples , did you try google? First start with a js function that uses .preventDefault(), on the submit, do your checks and fill a div with your message... – Rmaxx Apr 18 '22 at 22:59

2 Answers2

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!

0

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>
Jon P
  • 19,442
  • 8
  • 49
  • 72