[英]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.