![](/img/trans.png)
[英]How do I trigger HTML5 validation error popup when custom validation message is set manually?
[英]HTML5 Validation: different behavior when custom validation message is set
我一直在处理此注册表单,在其中使用HTML5的验证检查。 为了在您不匹配所需的模式时显示自定义错误消息,我关注了这篇文章: 如何更改或删除HTML5表单验证默认错误消息?
现在所有功能都可以正常工作,除了这个我无法解决的烦人的问题:匹配模式时,弹出气泡不会自动消失。 为了进一步解释该问题,我制作了这个JSFiddle: http : //jsfiddle.net/Jeroen88/Lujt490o/ ,其代码如下:
<form>
<fieldset>
<legend>Custom message</legend>
<label for="password1">Password 1:</label>
<input type="password" pattern=".{4,}" required id="password1"
oninvalid="setCustomValidity('Password must be at least 4 characters')"
onchange="try{setCustomValidity('')}catch(e){}" />
<input type="submit" />
</fieldset>
</form>
如您所见,即使在匹配模式之后,验证消息仍然会出现。 使用默认错误消息不能描述此行为!
<form>
<fieldset>
<legend>Without custom message</legend>
<label for="password2">Password 2:</label>
<input type="password" pattern=".{4,}" required id="password2" />
<input type="submit" />
</fieldset>
</form>
所以我的问题是:如何使自定义验证消息的行为与默认消息相同?
通过将'onchange'更改为'oninput'并让自定义函数正确处理setCustomValidity可以解决该问题 ,例如Rikin Patel 对另一个问题的回答:
HTML:
<input type="text" pattern="[0-9]{10}" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" />
JAVASCRIPT:
function InvalidMsg(textbox) { if(textbox.validity.patternMismatch){ textbox.setCustomValidity('please enter 10 numeric value.'); } else { textbox.setCustomValidity(''); } return true; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.