简体   繁体   English

javascript验证电话

[英]javascript validation telephone

I have this function which objective is to validate a phone number introduced by a user with base in 2 regex variables. 我有这个功能,目的是验证用户使用2个正则表达式变量为基础的电话号码。

if the user has the country Sweden selected and introduces 212341512 the warning shouldnt appear since the phone is valid however that doesnt happen. 如果用户选择了瑞典国家/地区并引入了212341512,则该警告不应出现,因为该电话有效,但是不会发生。 i still get the warning message to appear even if the phone number matches the conditions in the variable indicators. 即使电话号码符合可变指示器中的条件,我仍然会出现警告消息。

function validateTelephone() {
            var telephone = document.getElementById('txtTel');
            var country=document.getElementById('ddCountry');
            var indicators= /^(21|22)\d{7}$/;

                   if (country.value == "Sweden") {
                        if (!indicators.test(telephone.value)) {
                        document.getElementById('lblWarning').style.color = "red";
                        document.getElementById('lblWarning').innerHTML = 'Invalid Telephone Number';
                        } else {
                        document.getElementById('lblWarning').innerHTML = '';
                        }
                    } else{
                     document.getElementById('lblWarning').innerHTML = ' ';
                    }

         }

if you guys have any suggestions about my code or a way to solve this problem i'd appreciate that since im new to this language 如果你们对我的代码有什么建议或解决此问题的方法,我将不胜感激,因为这是我的新语言

I would use libphonenumber, which has a JavaScript library already made for you. 我会使用libphonenumber,它已经为您制作了一个JavaScript库。

https://code.google.com/p/libphonenumber/ https://code.google.com/p/libphonenumber/

As for your code, the regex is correct, and does match the number provided. 至于您的代码,正则表达式是正确的,并且与提供的数字匹配。

Please try using Chrome's JavaScript debugger. 请尝试使用Chrome的JavaScript调试器。 (right-click page, inspect element, sources tab). (右键单击页面,检查元素,源选项卡)。 Put in a breakpoint at the beginning of your function and see what happens. 在函数的开头放置一个断点,看看会发生什么。 Check the values of variables. 检查变量的值。

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

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