...

View Full Version : Phone Validation Javascript



leroybobbins
01-24-2009, 06:54 AM
Hi,

I have a form on my website and I want to validate the phone field. I found a good script to do it but I need to combine the script with the other validation that I have on my form. Can you help me add this phone validation script into the other validations that I have so that it is just one javascript?

Here is the phone validation script:
<script language = "Javascript">
/**
* DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function trim(s)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not a whitespace, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (c != " ") returnString += c;
}
return returnString;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}

function checkInternationalPhone(strPhone){
var bracket=3
strPhone=trim(strPhone)
if(strPhone.indexOf("+")>1) return false
if(strPhone.indexOf("-")!=-1)bracket=bracket+1
if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
var brchr=strPhone.indexOf("(")
if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function ValidateForm(){
var Phone=document.frmSample.txtPhone

if ((Phone.value==null)||(Phone.value=="")){
alert("Please Enter your Phone Number")
Phone.focus()
return false
}
if (checkInternationalPhone(Phone.value)==false){
alert("Please Enter a Valid Phone Number")
Phone.value=""
Phone.focus()
return false
}
return true
}
</script>

Here are the validations for the other fields:
<script type="text/JavaScript">

function validate_form(){

err = 'The following fields are not correct filled:\n';



if (document.form1.name.value == ''){
err += 'No First Name.\n';

}



if (document.form1.from.value == ''){
err += 'No Email Address.\n';

}



if (document.form1.elements['custom State'].value == ''){
err += 'No State.\n';

}



if (document.form1.elements['custom Phone'].value == ''){
err += 'No Phone.\n';

}



if (emailCheck(document.form1.from.value) == false){

err += 'No Valid email.\n';

}

if (document.form1.terms.checked != true){

err += 'You did not agree with the terms.\n';

}



if (err != 'The following fields are not correct filled:\n'){

alert (err);

return false;

}


else{
return true;
}
}
var str_vars = '';
function all_fields(){
str_vars = '';
el = document.form1;
for (var i = 0; i < el.elements.length; i++) {
if (el.elements[i].value != '')
str_vars += el.elements[i].name+'='+el.elements[i].value+'&';
}
str_vars = str_vars.substr(0,str_vars.length-15);;
}

</script>

Thank you,
Leroy

Philip M
01-24-2009, 08:44 AM
You can collapse all that into one line:-

if (/(^[0-9\s\-\+]{10,})$/gi.test(Phone.value)) { /// telephone number, only digits, space, hyphen and plus sign allowed. Minimum of 10 characters.
alert ("Valid Phone Number");

or of course you can reverse the logic:-

if (!/(^[0-9\s\-\+]{10,})$/gi.test(Phone.value)) { /// telephone number, only digits, space, hyphen and plus sign allowed. Minimum of 10 characters.
alert ("Invalid Phone Number");

As with all validations I suggest you add before the regex check:-

Phone.value = Phone.value.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
Phone.value = Phone.value.replace(/\s+/g," "); // replace multiple spaces by a single space

Obviously this is not bullet-proof as the user can enter e.g. ten plus signs or ten hyphens. But in my experience it is not worth while to validate telephone numbers excessively as the greatest and most obvious risk of error is that the user enters a (plausible) number which is simply wrong. In fact I quite often do this deliberately as my number is ex-directory and I want to to avoid spam phone calls.

<script language = "Javascript"> is deprecated and should give you a clue that this is old (and very cumbersome and inefficient) code. Use <script type = "text/javascript"> instead.

Validations like this:-

if (document.form1.name.value == '') {
err += 'No First Name.\n';
}

are virtually useless as a single space (or any other character such as ?) will return true.


Caller: "I deleted a file from my PC last week and I have just realised that I need it. If I turn my system clock back two weeks will I have my file back again?".

leroybobbins
01-24-2009, 09:07 AM
Thank you Phillip for your help. I know very little about programming. So, can you show me exactly where to plop that if statement into my current form validation so that it validates the ['custom Phone'].value field?

Here is what I have so far:

<script type="text/JavaScript">

function validate_form(){

err = 'The following fields are not correct filled:\n';



if (document.form1.name.value == ''){
err += 'No First Name.\n';

}



if (document.form1.from.value == ''){
err += 'No Email Address.\n';

}



if (document.form1.elements['custom State'].value == ''){
err += 'No State.\n';

}



if (document.form1.elements['custom Phone'].value == ''){
err += 'No Phone.\n';

}



if (emailCheck(document.form1.from.value) == false){

err += 'No Valid email.\n';

}

if (document.form1.terms.checked != true){

err += 'You did not agree with the terms.\n';

}



if (err != 'The following fields are not correct filled:\n'){

alert (err);

return false;

}


else{
return true;
}
}
var str_vars = '';
function all_fields(){
str_vars = '';
el = document.form1;
for (var i = 0; i < el.elements.length; i++) {
if (el.elements[i].value != '')
str_vars += el.elements[i].name+'='+el.elements[i].value+'&';
}
str_vars = str_vars.substr(0,str_vars.length-15);;
}

</script>

Philip M
01-24-2009, 09:13 AM
Replace this:-

if (document.form1.elements['custom Phone'].value == ''){
err += 'No Phone.\n';
}

By this:-

var Phone = document.form1.elements['custom Phone'].value;
Phone = Phone.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
Phone = Phone.replace(/\s+/g," "); // replace multiple spaces by a single space
if (!/(^[0-9\s\-\+]{10,})$/gi.test(Phone)) { /// telephone number, only digits, space, hyphen and plus sign allowed. Minimum of 10 characters.
err += "Invalid Phone Number\n";
}

Likewise, you could replace the fairly useless:-

(document.form1.elements['custom State'].value == ''){
err += 'No State.\n';
}

By:-

var stateCode = form1.elements['custom State'].value;
if(!/^(A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[ANU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$/i.test(stateCode)) {
err += "Invalid or no State specified\n";
}


Remember that JavaScript form validation only provides convenience for users, not security. This means that JavaScript should be used as an "enhancement", not as a requirement. So your form should not be dependent on JavaScript alone to perform your validation. Instead, whatever server-side language you use to process the form (PERL, ASP, PHP, etc.) should also perform the same validation. Otherwise, people will be able to bypass your validation (and even possibly inject malicious code) simply by disabling JavaScript.


You can test your regular expressions at: http://www.claughton.clara.net/regextester.html

leroybobbins
01-24-2009, 05:25 PM
Thanks again Philip for the help.

I did what you said and replaced this:

if (document.form1.elements['custom Phone'].value == ''){
err += 'No Phone.\n';
}

By this:-

var Phone = document.form1.elements['custom Phone'].value;
Phone = Phone.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
Phone = Phone.replace(/\s+/g," "); // replace multiple spaces by a single space
if (!/(^[0-9\s\-\+]{10,})$/gi.test(Phone)) { /// telephone number, only digits, space, hyphen and plus sign allowed. Minimum of 10 characters.
err += "Invalid Phone Number\n";
}

I just installed tested it but it is not working. I'm entering a valid phone number but it is giving me the "Invalid Phone Number" error.

Please advise.

Thanks,
Leroy

Philip M
01-24-2009, 06:36 PM
I just installed tested it but it is not working. I'm entering a valid phone number but it is giving me the "Invalid Phone Number" error.


It works for me. Please specify the exact phone number you are entering and which returns invalid.

And what do you get (exactly) when you add this alert:-

var Phone = document.form1.elements['custom Phone'].value;
alert (Phone);

leroybobbins
01-24-2009, 08:53 PM
It works for me. Please specify the exact phone number you are entering and which returns invalid.

I'm entering any 10 digit phone number and the error occurs. Here is one specifically that I entered "8012728989".

If I type in one digit ie. "3" then the error does not pop up.


And what do you get (exactly) when you add this alert:-

var Phone = document.form1.elements['custom Phone'].value;
alert (Phone);

I don't know what you mean by this. Do you mean to add the alert like this:

var Phone = document.form1.elements['custom Phone'].value;
alert (Phone);
Phone = Phone.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
Phone = Phone.replace(/\s+/g," "); // replace multiple spaces by a single space
if (!/(^[0-9\s\-\+]{10,})$/gi.test(Phone)) { /// telephone number, only digits, space, hyphen and plus sign allowed. Minimum of 10 characters.
err += "Invalid Phone Number\n";
}

Philip M
01-24-2009, 09:41 PM
I'm entering any 10 digit phone number and the error occurs. Here is one specifically that I entered "8012728989".

If I type in one digit ie. "3" then the error does not pop up.



I don't know what you mean by this. Do you mean to add the alert like this:

var Phone = document.form1.elements['custom Phone'].value;
alert (Phone);
Phone = Phone.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
Phone = Phone.replace(/\s+/g," "); // replace multiple spaces by a single space
if (!/(^[0-9\s\-\+]{10,})$/gi.test(Phone)) { /// telephone number, only digits, space, hyphen and plus sign allowed. Minimum of 10 characters.
err += "Invalid Phone Number\n";
}


Well, I am testing with the following script:-


<script type = "text/javascript">
var Phone = "8012728989";
Phone = Phone.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
Phone = Phone.replace(/\s+/g," "); // replace multiple spaces by a single space
if (!/(^[0-9\s\-\+]{10,})$/gi.test(Phone)) { /// telephone number, only digits, space, hyphen and plus sign allowed. Minimum of 10 characters.
alert ("Invalid Phone Number");
}

else {
alert ("Valid Phone Number");
}
</script>

If you run that, you will find that the phone number is (as expected) valid.

This suggests that the phone number as entered by the user is not being passed to the function correctly. Especially when "If I type in one digit ie. "3" then the error does not pop up." That is why I asked you to include an alert (for testing purposes). Do that, report back, that will give us a clue. I do mean add it to the script as I indicated and you say.

If you are not au fait with Javascript alerts then I fear that you are trying to run before you can walk.

Please also post the relevant HTML, that is the <input statement where the user enters the phone number into a text box.

Finally, please confirm that the validation worked before these alterations were made, and that leaving the phone field empty resulted in the relevant error message "No phone".

mark2mark
10-30-2011, 03:21 PM
Hi all!

I guess it's better to check the location of the number rather than just checking if it's a valid number. That way we can ensure that the user is not entering a imaginary number which has the same length which a number would normally have. I got a javascript to do that. I wrote a blog on validating the location of the phone number. It can detect the country and state (US numbers only) of the phone number. It can also detect toll free/ premium numbers). You can check my blog below
Javascript phone number location validation (http://ipowerblogger.com/javascript/validate-phone-number-location-using-javascript/#content)

I hope it helps everyone :-)

Demon Templates
12-21-2011, 11:45 AM
Hi all!

I guess it's better to check the location of the number rather than just checking if it's a valid number. That way we can ensure that the user is not entering a imaginary number which has the same length which a number would normally have. I got a javascript to do that. I wrote a blog on validating the location of the phone number. It can detect the country and state (US numbers only) of the phone number. It can also detect toll free/ premium numbers). You can check my blog below
Javascript phone number location validation (http://ipowerblogger.com/javascript/validate-phone-number-location-using-javascript/#content)

I hope it helps everyone :-)

The requested page "/javascript/validate-phone-number-location-using-javascript/" could not be found.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum