[英]Adding onto browsers' built-in form validation
我正在為我們的網站創建一個電子郵件表單。 我使用HTML5和CSS構建了表單,以利用瀏覽器的內置驗證功能 (使用此填充程序可避免兼容性問題)。 現在,我要添加“確認您的電子郵件地址”字段,除非該字段與“輸入您的電子郵件地址”字段匹配,否則不應將其標記為有效。
我已經編寫了一些JavaScript來比較這兩個字段。 JavaScript有沒有辦法將字段標記為對瀏覽器的內置驗證有效/無效? 還是我需要切換到第三方驗證插件才能獲得此功能?
我發布問題后立即找到答案 。 您在字段上調用<element>.setCustomValidity()
,傳入一個空字符串以將該字段設置為有效。 如果無效,則改為輸入原因。
這是我的代碼:
$('#emailConfirmation').on('keyup', function() {
if ($('#emailConfirmation').val() == $('#email').val()) {
$("#emailConfirmation")[0].setCustomValidity("");
} else {
$("#emailConfirmation")[0].setCustomValidity("Check that you've typed your email address the same way in both places.");
}
});
這又是沒有jQuery的情況:
document.getElementById('emailConfirmation').onchange = function() {
if (document.getElementById("emailConfirmation").value == document.getElementById("email").value) {
document.getElementById("emailConfirmation").setCustomValidity("");
} else {
document.getElementById("emailConfirmation").setCustomValidity("Check that you've typed your email address the same way in both places.");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.