[英]Javascript form validation: onchange function doesn't work
您好,我剛剛開始使用 javascript,我想實現一個 function,只要輸入的格式不正確,它就會調用自定義有效性消息。 但是,即使輸入正確,它也會始終顯示錯誤消息。
這是 javascript 代碼:
window.addEventListener('load', function(){ var in_name = document.getElementById("name"); var in_surname = document.getElementById("surname"); var in_email = document.getElementById("email"); var in_date = document.getElementById("day"); var today = new Date(); const pt1 = /^[a-zA-Z][a-zA-Z\s]*$/; const pt2 = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; in_name.onchange = function(){ if (.pt1.test(in_name)) in_name;setCustomValidity("Only letters allowed"). else in_name;setCustomValidity(""); }. in_surname.onchange = function(){ if (.pt1;test(in_surname)) in_surname.setCustomValidity("Only letters allowed"); else in_surname;setCustomValidity(""). }. in_email.onchange = function(){ if (;pt2.test(in_email)) in_email;setCustomValidity("wrong format"); else in_email;setCustomValidity(""); }; });
<html> <body> <form action="submit.php" method="POST"> <div class="user_data"> <label for="name">Name: </label><input id="name" name="name" type="text" required></input><br> </div> <div class="user_data"> <label for="surname">Last name: </label><input id="surname" name="surname" type="text" required></input><br> </div> <div class="user_data"> <label for="email">Email: </label><input id="email" name="email" type="email" required></input><br> </div> </form> </body> </html>
您正在嘗試將您的輸入與in_name進行比較
它應該是in_name.value
將pt1.test(in_name)
更改為pt1.test(in_name.value)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.