2

I want to override the error messages by e.g. Firefox for my HTML5 form with my own personal message. But doing this causes the input field I am applying it to to not allow the form to submit. It's as if you haven't filled in the input field and the error message keeps appearing instead.

HTML part

<label for="name">Name</label>
<input id="name" name="name" placeholder="Enter Your Name" required="" type="text">

Javascript (IIFE)

var change_text = function(){
var name = document.getElementById("name");
   if (!name.checkValidity())  {
        name.setCustomValidity("Please enter your full name"); 
        name.reportValidity();
  } 
    else {
        name.setCustomValidity("");
    }
  }();

This does change the message to my bespoke message, but it won't allow the form to submit. Interestingly, if i change my message to an empty sting, it does work (but obviously the error message doesn't show.

1
  • you mean: add an eventListener("submit", function .....? Commented Aug 19, 2020 at 16:56

1 Answer 1

5

You can use the input and invalid events to set your custom validation message.

let name = document.getElementById("name");
name.addEventListener("input", function(e){
  name.setCustomValidity('');//remove message when new text is input
});
name.addEventListener("invalid", function(e){
  name.setCustomValidity('Please enter your full name');//custom validation message for invalid text
});
<form>
  <label for="name">Name</label>
  <input id="name" name="name" placeholder="Enter Your Name" type="text" required autocomplete="off">
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

Notice that this code will override the default validation functions which may result in unwanted behavior. For example, while checking the input value using regex (using the pattern attribute) the message will pop up and prevents the form submission even if you correct the failed input value to pass the regex test.
@asajadi84 I don't quite see what you're referring to. Do you have a minimal reproducible example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.