[英]Do form validation in Javascript
我有一個表單,其中有一個字段,用戶在其中輸入他們的電話號碼,我們強制他們以 +34 開頭,后跟 9 位數字(該字段應該有總共 12 位數字),但是當我在 + 31 例如我拿起它好像是 +34,這是使用
<input type="text">
這是一個變量
let phone2 = phone.length
這是我在 Javascript 中使用的條件
if (phone != '+34' & phone2 < 12) {
evt.preventDefault ();
alert ('The phone number must start with +34 and have at least 12 digits');
}
如果有人可以幫助我
嘗試這個:
請注意, onblur
意味着當輸入字段失去焦點時將觸發測試函數。 因此,要運行測試,請鍵入一些內容,然后在輸入字段外單擊。
const $ = document.querySelector.bind(document); function test() { const phone = $('input').value; if (phone.substr(0, 3) !== '+34' || phone.length < 12) { alert('The phone number must start with +34 and have at least 12 digits'); } else { alert('good job'); } }
<input onblur="test()" placeholder="Phone (must begin with +34)" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.