Validating USA and UK phone numbers
The Ribbit API, and all the REST libraries, require you to submit phone numbers in RFC3966 format. This requires that the Ribbit US sales number (619) 916-2565 is submitted to the API as tel:16199162565
It's not always straightforward to validate phone numbers easily, ensuring that the country code is included. With the help of Javascript, we can make this a lot easier.
Here's the Javascript for the a PhoneNumber class. This class will help take a phone number in some format and attempt to translate it to the RFC3966. As with any code that relies on the use of regular expressions it may not cover all possible formats. Hopefully it's useful enough to give you a head start in building! If you want to add other countries to the validation you merely need to find and write a suitable regular expression... as well as add that to the validate function.
var PhoneNumber = function (phone, country) {
this.text=phone;
this.culture = country !== undefined ? country : "USA";
this.uri = "";
this.valid = this.validate();
return this;
};
PhoneNumber.prototype.usaRegEx=/^(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/;
PhoneNumber.prototype.ukRegEx=/^((0))(((1[0-9]{3})|(7[1-57-9][0-9]{2}))( )?([0-9]{3}[ -]?[0-9]{3})|(2[0-9]{2}( )?[0-9]{3}[ -]?[0-9]{4}))$/;
PhoneNumber.prototype.cleanRegex=/[^0-9]/g;
PhoneNumber.prototype.validate = function(){
var str = this.text;
var valid =false;
if (this.culture === "USA" && this.usaRegEx.test(str)){
str = str.replace(this.cleanRegex,"","g");
this.uri = "tel:1" + (str.substring(0,1)=="1" ? str.substring(1) :str );
valid = true;
}
if (this.culture === "UK" && this.ukRegEx.test(str)){
str = str.replace(this.cleanRegex,"","g");
this.uri = "tel:44" + (str.substring(0,1)=="0" ? str.substring(1) :str );
valid = true;
}
return valid;
};
With that code in place, here's an example of how we use the PhoneNumber class to query the phone.uri property to get a well formatted number:
var phone = new PhoneNumber("(619) 916-2565","USA");
if (phone.valid){
alert("The RFC3966 uri is " + phone.uri);
}
With this framework in place, we hope that you find all your telephone numbers conversion woes are behind you.
- san1t1's blog
- Login or register to post comments
-






