我正在进行表单验证,并且面临一个奇怪的问题。我想为required
字段显示自定义验证消息。
起初,我认为仅添加required
会检测到空输入并显示验证消息,但是由于添加了自定义验证(仅适用于非空输入),因此未显示。因此,添加required
属性时,是否不应该与自定义验证一起完成对空输入的验证?为什么它会被自定义验证完全覆盖?
另外,在下面的代码中,假设我输入输入为“ Hello”,然后单击“提交”。
显示了自定义验证消息,但是当我在“ Hello”之后按“ W”之类的字符时,将显示默认验证消息(“请在之后输入@”)。但是,我已经将setCustomValidity
设置为''
oninput
,那么它不应该显示默认消息吗?
我希望仅在输入无效(包括空输入)的情况下显示验证消息,而在提交表单(即单击“提交”按钮)时不显示验证消息。
请帮助我清除对自定义验证的理解。
function fn(e) {
var eq = document.querySelector("#uname");
var ev = eq.value;
if (ev === '') {
eq.setCustomValidity("Email can't be empty");
return false;
}
else if (!ev.match(/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/)) {
eq.setCustomValidity("Email entered is invalid");
return false;
}
eq.setCustomValidity("");
e.preventDefault();
}
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
username: <input type="email" name="usrname" id="uname" oninput="setCustomValidity('')" required />
<input type="submit" onclick="fn(event)">
</form>
<p><strong>Note:</strong> The required attribute of the input tag is not
supported in Internet Explorer 9 and earlier versions.</p>
</body>
</html>