1

I found this answer for changing error message for invalid values How can I change or remove HTML5 form validation default error messages?.

I need to show different message for value less than min and more than max.

<input type="number" name="test" step="any" min="0.01" max="10.0">

If user enters -1, it should say "Please enter positive value".

If user enters 20, it should say "Value cannot be more than 10".

ritesh
  • 11
  • 1
  • 2
  • what's wrong with the answer you linked? Just make general message `oninvalid="setCustomValidity('Enter a number beween 0.01 and 10 ')"` – Andrew Lohr Apr 17 '18 at 18:40
  • The actual use case is complex like, "you cannot enter more than 10 because your limit is expired". – ritesh Apr 17 '18 at 19:16

2 Answers2

0

There may be some fancy API-driven way to do it, but if the title is displayed when the input doesn't match a pattern, you can just modify the the title on change.

To support decimals, you'll need some fancier regex.

*I included the form tag so the validation would work in the snippet

document.querySelector('input').addEventListener('change', (e) => {
  if (e.target.value > 10) {
    e.target.setAttribute('title', "Value cannot be more than 10");
  } else if (e.target.value < 0) {
    e.target.setAttribute('title', "Please enter a positive value");
  } else {
    e.target.setAttribute('title', "Please enter a number");
  }
})
<form><input type="text" required="" pattern="10|[0-9]" value="" title="This is an error message" /></form>
wassona
  • 319
  • 1
  • 9
0

With the HTML5 form validation (from your link) you can use a custom message by using the invalid event listener on the input element.

var myInput = document.getElementById("myInput");
myInput.addEventListener("invalid", validate);
myInput.addEventListener("keyup", validate);

function validate() {
  var val = parseFloat(this.value);
  var min = parseFloat(this.min);
  var max = parseFloat(this.max);
  
  if (val < min) {
    this.setCustomValidity('Please enter a positive number');
  } else if (val > max) {
    this.setCustomValidity('Value cannot be more than ' + max);
  } else {
    this.setCustomValidity("");
  }
}
<form>
  <input id="myInput" type="number" name="test" step="any" min="0.01" max="10.0">
  <button type="submit">Submit</button>
</form>
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38