简体   繁体   English

在 Javascript 中进行表单验证

[英]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我有一个表单,其中有一个字段,用户在其中输入他们的电话号码,我们强制他们以 +34 开头,后跟 9 位数字(该字段应该有总共 12 位数字),但是当我在 + 31 例如我拿起它好像是 +34,这是使用

<input type="text">

This is a variable这是一个变量

let phone2 = phone.length

This is the contidion I am using in Javascript这是我在 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.请注意, onblur意味着当输入字段失去焦点时将触发测试函数。 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)" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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