[英]HTML5 Form Validation
關於 HTML5 表單驗證,我有兩個主要問題。
1-我使用此代碼更改輸入的驗證消息
$$('INPUT').each(function(input)
{
input.oninvalid = function(event)
{
event.target.setCustomValidity('');
if (!event.target.validity.valid) event.target.setCustomValidity('Please Fill');
};
}
這種方法有很大的問題。 如果輸入無效,則提交表單時,會附加一條錯誤消息。 所以它不會驗證新的輸入。 即使在更正並再次提交后,它也不會讓表單被提交,因為消息仍然是附加的。 所以 event.target.setCustomValidity('') 將刪除消息並且表單需要再次提交。 二更正后提交。
我找不到糾正這種行為的方法。
2-如何完全隱藏或禁用這些工具提示但仍使用表單驗證。 有時候想用css無效和有效的偽類,但是還是顯示這些提示。
我在提交按鈕上找到了 formnovalidate ,然后我可以在提交之前手動檢查每個輸入的有效性。 有更好的主意嗎?
關於問題1:
我有輸入
<input name="VoucherCode" id="VoucherCode" type="text" pattern="(1[0-9]{9})|(2[0-9]{9})" value="">
並改進了默認消息
$("#VoucherCode").on("invalid", function (event) {
event.target.setCustomValidity('The format of Voucher Code is not correct.')
});
但是,這也遇到了與您相同的問題:如果用戶第一次嘗試錯誤,正確的響應仍會顯示無效的模式消息。
我根據@Pointy的建議修復了此問題:
$("#VoucherCode").on("invalid", function (event) {
event.target.setCustomValidity('The format of Voucher Code is not correct.')
}).bind('blur', function (event) {
event.target.setCustomValidity('');
});
(有點晚了)但解決方案可能就在那里!
發生了什么:由於您自定義錯誤消息event.target.setCustomValidity("...")
中的屬性element.validity.customError
是true
; 總是返回false
的reportValidity並且提交無效
我做了什么? 當用戶更改輸入( event.on Change
)時 - 我設置了默認錯誤消息event.target.setCustomValidity('');
這將告訴瀏覽器繼續工作而不會出現自定義錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.