简体   繁体   English

电话号码长度验证JavaScript

[英]phone number length validate JavaScript

I was trying to validate my phone number. 我正在尝试验证我的电话号码。 Everything is working except the validate 10 digit part 除验证10位数部分外,其他所有功能均正常工作

 if ($(".phone").val() == "") { phoneerror = "Please enter phone number"; } else if (!($.isNumeric($(".phone").val())) && $(".phone").val() != "") { phoneerror = "this field cannot contain letters"; } else if ($(".phone").val().length !== 10) { phoneerror = "Must be 10 Digits"; } else { phoneerror = ""; } console.log(phoneerror); 
 <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <input type="text" class="phone" value="12345"> 

can someone please tell me what is the wrong with my code 有人可以告诉我我的代码有什么问题吗

Please check this sample. 请检查此样本。 You should position number length before other validations also you can use maxlength html attribute. 您应该在其他验证之前放置数字长度,也可以使用maxlength html属性。

 function validatePhone(){ if($(".phone").val() == ""){ phoneerror = "Please enter phone number"; } else if ($(".phone").val().length !== 10){ phoneerror = "Must be 10 Digits"; } else if(!($.isNumeric($(".phone").val())) && $(".phone").val() != ""){ phoneerror = "this field cannot contain letters"; }else { phoneerror = ""; } console.log(phoneerror); return phoneerror; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="phone" type="text" onkeyup="validatePhone(this);" maxlength="10"/> 

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

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