用途
setCustomValidity):
document.addEventListener("DOMContentLoaded", function() { var elements = document.getElementsByTagName("INPUT"); for (var i = 0; i < elements.length; i++) { elements[i].oninvalid = function(e) { e.target.setCustomValidity(""); if (!e.target.validity.valid) { e.target.setCustomValidity("This field cannot be left blank"); } }; elements[i].oninput = function(e) { e.target.setCustomValidity(""); }; }})我已按照@itpastorn在评论中的建议,从Mootools更改为VanillaJavascript,但如有必要,您应该可以设计出等效的Mootools。
我在这里更新了代码,其
setCustomValidity工作方式与我最初回答时所了解的略有不同。如果
setCustomValidity设置为空字符串以外的任何其他值,则将导致该字段被视为无效;因此,您必须在测试有效性之前清除它,而不能只是设置它而忘记。
正如下面@thomasvdb的注释中指出的那样,您需要在某些事件之外清除自定义有效性,
invalid否则可能需要通过
oninvalid处理程序进行额外的清除操作。



