[英]Javascript phone number validation
I need to validate a phone number in javascript.我需要在 javascript 中验证电话号码。 The requirements are:
要求是:
they should be 10 digits, no comma, no dashes, just the numbers, and not the 1+ in front
它们应该是 10 位数字,没有逗号,没有破折号,只有数字,而不是前面的 1+
this is what I wrote so far这是我到目前为止所写的
function validatePhone(field,alerttxt) {
with (field) {
if(value.length > 10) {
alert(alerttext);
return false;
}
for(i = 0; i < value.length; i++) {
if(parseInt(value[i]) == NaN) {
alert(alerttxt);
return false;
}
}
return true;
}
}
function validateForm(thisform) {
if (validatePhone(phone,"Invalid phone number")==false) {
phone.focus();
return false;
}
}
}
<form action="post.php" method="post" id="contactform" onsubmit="return validateForm(this)">
<ol>
<label for="phone">Your phone <span class="red"></span></label>
<input id="phone" name="phone" class="text" />
</li>
</ol>
</form>
but, obviously it doesn't work.但是,显然它不起作用。 How can I write the
validatePhone()
function so that it works?如何编写
validatePhone()
函数以使其正常工作?
phone = phone.replace(/[^0-9]/g, '');
if(phone.length != 10) {
alert("not 10 digits");
} else {
alert("yep, its 10 digits");
}
This will validate and/or correct based on your requirements, removing all non-digits.这将根据您的要求进行验证和/或更正,删除所有非数字。
Google's libphonenumber is very helpful for validation and formatting of phone numbers all over the world. Google 的libphonenumber对验证和格式化世界各地的电话号码非常有帮助。 It is easier, less cryptic, and more robust than using a RegEx, and it comes in JavaScript, Ruby, Python, C#, PHP, and Objective-C flavors.
与使用 RegEx 相比,它更容易、更不神秘且更健壮,并且它有 JavaScript、Ruby、Python、C#、PHP 和 Objective-C 版本。
You could use Regular Expressions:您可以使用正则表达式:
function validatePhone(field, alerttext) {
if (field.match(/^\d{10}/)) {
return true;
}
alert(alerttext);
return false;
}
Code to except only numbers braces and dashes代码除了数字大括号和破折号
function DoValidatePhone() {
var frm = document.forms['editMemberForm'];
var stripped = frm.contact.value;
var isGoodMatch = stripped.match(/^[0-9\s(-)]*$/);
if (!isGoodMatch) {
alert("The Emergency Contact number contains invalid characters." + stripped);
return false;
}
}
Fixed function:固定功能:
function validateForm(thisform) {
if (validatePhone(thisform.phone,"Invalid phone number")==false) {
thisform.phone.focus();
return false;
}
return true;
}
在输入标签中直接添加您想要的格式的模式。
<input id="phone" name="phone" pattern="\d{10}" class="text" />
function validate(phoneString){
reg = /^([+|\d])+([\s|\d])+([\d])$/;
return reg.test(phoneString);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.