4

It seems dynamically adding customValidity is breaking the pattern validation. Is there any way to fix this issue using Javascript?

<html>
<head>
<title>Append validation issue</title>
<script>
function dothis(){
    var f = document.createElement("form");
    var i = document.createElement("input");
    i.type = "text";
    i.pattern = "[A-Z]{3}";
    i.setCustomValidity("watch me break");
    var s = document.createElement("input")
    s.type = "submit";
    f.appendChild(i);
    f.appendChild(s)
    document.getElementById("core").appendChild(f);
}
</script>
</head>
<body>
<div onclick="dothis()">click</div>
<div id="core"></div>
</body>
</html>
K3NN3TH
  • 1,458
  • 2
  • 19
  • 31

1 Answers1

4

Using setCustomValidity will set the customError property to true, and thus the element will always be invalid.

So we should use setCustomValidity when text is invalid, and clear when valid.

function dothis(){
    var f = document.createElement("form");
    var i = document.createElement("input");
    i.type = "text";
    i.pattern = "[A-Z]{3}";
    i.oninput = function() {
        this.setCustomValidity('');
    }
    i.oninvalid = function() {
        this.setCustomValidity("watch me break");
    }
    var s = document.createElement("input")
    s.type = "submit";
    f.appendChild(i);
    f.appendChild(s)
    document.getElementById("core").appendChild(f);
}

https://jsfiddle.net/oL07go4s/

K3NN3TH
  • 1,458
  • 2
  • 19
  • 31
Rickkwa
  • 2,197
  • 4
  • 23
  • 34
  • Why is nobody mentioning that we should clear `setCustomValidity` ? I've wasted so much time ... Thanks a lot mate. – NecipAllef Nov 01 '16 at 20:02