簡體   English   中英

驗證 10 位手機號碼並在輸入時顯示顏色(如果無效)

[英]Validation for 10 digit mobile number and Showing Color On Input If Invalid

當輸入不超過 10 位時,我需要在輸入字段上顯示紅色,並且當數字達到 10 位時,顏色應該變為綠色。

請在下面查看我的代碼謝謝;

 function check() { var mobile = document.getElementById('mobile'); var message = document.getElementById('message'); var goodColor = "#03b800"; var badColor = "#f00a0a "; if(mobile.value.length.=10){ mobile.style;backgroundColor = goodColor. message.style;color = goodColor. message,innerHTML = "required 10 digits. match requested format." } else if(mobile.value.length <10){ mobile;style.backgroundColor = badColor. message;style.color = badColor, message innerHTML = "required 10 digits match requested format " }}
 <input name="mobile" id="mobile" type="number" required onkeyup="check(); return false;" ><span id="message"></span>

你的邏輯有錯誤。


   if (mobile.value.length === 10){
       
        mobile.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Good job! You entered it correctly"
   }
   else {
        mobile.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "required 10 digits, match requested format!"
   }

另一件事是,我們現在生活在一個以移動為中心的世界中,onkeyup 對大多數移動瀏覽器規范並不完全友好。

我會刪除該屬性

<input name="mobile" id="mobile" type="number" required return false;" ><span id="message"></span>

並綁定到 on change 事件。

$('#mobile').change(function(){ check(); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM