Skip to content
Advertisement

SetCustomValidity not working

I am trying to create a custom error message when a number which is too high or low is entered in the “size” element. However, I am unable to make this work. I am a beginner so a solution which involves the least changes to my existing code would be most appreciated.

function autoFillcost() {
  var size = document.getElementById("size").value;
  if (size <= 25)
    document.getElementById("cost").value = "£100";
  else if (size >= 26 && size <= 50)
    document.getElementById("cost").value = "£200";
  else
    document.getElementById("cost").value = "£300";
}

function sizeValidate() {
  var size = document.getElementById("size");
  if (!size.checkValidity()) {
    size.setCustomValidity("ERROR!");
  } else {
    size.setCustomValidity("");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<body>

  <form>

    Group Size:<input type="number" min="6" max="200" id="size" onblur="autoFillcost();sizeValidate();" required>

    <p>Cost:<input type="text" id="cost"></p>

    <p id="demo"></p>

  </form>

</body>

</html>

Advertisement

Answer

The problem with setCustomValidity is, that it does only work once you submit the form.

function autoFillcost() { 
var size = document.getElementById("size").value;
if (size <= 25)
document.getElementById("cost").value = "£100";
else if (size >= 26 && size <= 50)
document.getElementById("cost").value = "£200";
else
document.getElementById("cost").value = "£300";
}

function sizeValidate() {
var size = document.getElementById("size");

    if (!size.checkValidity()) {

        size.setCustomValidity("ERROR!");
    } else {
        size.setCustomValidity("");

    } 
}
button {
	padding:6px; 
	cursor:pointer;
}
input {
	padding:5px; 
	border:1px solid #aaa;
    box-shadow: 0px 0px 3px #ccc, 0 10px 15px #eee inset;
    border-radius:2px;
}
input:valid {
	background-color: white;
}
input:invalid {
	background-color: lightpink;
}
<form>

Group Size:<input type="number" min="6" max="200" id="size"  onblur="autoFillcost();sizeValidate();" required />

<p>Cost:<input type="text" id="cost"></p>

<p id="demo"></p>
<button type="submit">Submit</button>
</form>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement