简体   繁体   中英

Do form validation in Javascript

I have a form in which I have a field where the user enters their phone number and we force them to start with +34 followed by 9 digits (12 digits in total are what that field should have), but then when I change at +31 for example I pick it up as if it were +34, this is using a

<input type="text">

This is a variable

let phone2 = phone.length

This is the contidion I am using in Javascript

if (phone != '+34' & phone2 < 12) {
        evt.preventDefault ();
        alert ('The phone number must start with +34 and have at least 12 digits');
        
      }

If anyone can help me

Try this:

Note that onblur means that the test function will fire when the input field loses focus. So, to run the test, type something and then click outside the input field.

 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)" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM