Skip to content

Instantly share code, notes, and snippets.

@bameyrick
Last active August 10, 2016 10:05
Show Gist options
  • Select an option

  • Save bameyrick/8ccdf53daf12d2570326 to your computer and use it in GitHub Desktop.

Select an option

Save bameyrick/8ccdf53daf12d2570326 to your computer and use it in GitHub Desktop.
ES6 Validate a UK Telephone number
export default function ValidateUKPhone(number) {
const errorMessages = [
"Please enter a UK telephone number without the country code.",
"UK telephone numbers should contain 10 or 11 digits.",
"The telephone number should start with a 0.",
"The telephone number is either invalid or inappropriate."
];
let telnum = `${number}`;
const countryCodeExpression = /^(\+)[\s]*(.*)$/;
if(countryCodeExpression.test(telnum) == true) {
return errorMessages[0];
}
while (telnum.indexOf(" ") != -1) {
telnum = telnum.slice(0, telnum.indexOf(" ")) + telnum.slice(telnum.indexOf(" ") + 1)
}
while (telnum.indexOf("-") != -1) {
telnum = telnum.slice(0, telnum.indexOf("-")) + telnum.slice(telnum.indexOf("-") + 1)
}
const lengthExpression = /^[0-9]{10,11}$/;
if (lengthExpression.test(telnum) != true) {
return errorMessages[1];
}
const startsWithZeroExpression = /^0[0-9]{9,10}$/;
if (startsWithZeroExpression.test(telnum) != true) {
return errorMessages[2];
}
const formatExpression = new Array();
formatExpression.push(/^(0113|0114|0115|0116|0117|0118|0121|0131|0141|0151|0161)(4960)[0-9]{3}$/);
formatExpression.push(/^02079460[0-9]{3}$/);
formatExpression.push(/^01914980[0-9]{3}$/);
formatExpression.push(/^02890180[0-9]{3}$/);
formatExpression.push(/^02920180[0-9]{3}$/);
formatExpression.push(/^01632960[0-9]{3}$/);
formatExpression.push(/^07700900[0-9]{3}$/);
formatExpression.push(/^08081570[0-9]{3}$/);
formatExpression.push(/^09098790[0-9]{3}$/);
formatExpression.push(/^03069990[0-9]{3}$/);
for(let i = 0, l = formatExpression.length; i < l; i++) {
if(formatExpression[i].test(telnum)) {
return errorMessages[3];
}
}
const formatExpression2 = (/^(01|02|03|05|070|071|072|073|074|075|07624|077|078|079)[0-9]+$/);
if (formatExpression2.test(telnum) != true) {
return errorMessages[3];
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment