Phone Number Validator
by Sam Fereday
HTML
<input id="number" value="+44 7532 070 370" />
<button id="check">
Check
</button>
<div id="output">Error!</div>
CSS
body {
font: 75%/1.4em arial;
}
#output {
padding: 1em;
margin-top: 1em;
color: #fff;
background: #990000;
display: none;
}
JavaScript
// TODO: validate phone number only containers the following characters: 0123456789+()
// then strip all non-digit characters and confirm the length of the number is at least minlength and at most maxlength
var n = document.getElementById("number");
var o = document.getElementById("output");
var check = document.getElementById("check");
/* Test numbers
0+1234d567
0123f45hsdsadasdasdh6789ddddd
01234+567()89(0)
012345678
*/
var minlength = 9;
var maxlength = 16;
var containsNonNumeric;
var containsSpecial;
check.addEventListener("click", function(){
// Get latest value
n = document.getElementById("number");
// Remove whitespace
n.value = n.value.replace(/\s+/g, '');
// Hide error if not already
o.style.display = "none";
var invalidStr = /\d([^\+]\D+)|([^\+][^\(][^\)][^\(\)]\D+)/gm; // This is wrong
var invalidType = /^([^\d]).*/gm;
var containsInvalid = invalidStr.exec(n.value);
var notNumerical = invalidType.exec(n.value);
// Perform checks
if(notNumerical && notNumerical.length > 0) {
console.log("Not allowed", notNumerical);
o.style.display = "block";
o.innerHTML = "Phone number has invalid characters.";
return false;
}
// Contains invalid characters
if(n.value.length === 0 || containsInvalid) {
console.error("Phone number not valid.");
o.style.display = "block";
o.innerHTML = "Phone number not valid.";
return false;
}
console.log("First pass accepted", n.value);
// Numbers don't match require length
if(n.value.length < minlength || n.value.length > maxlength) {
console.error("Phone number length not valid.");
o.style.display = "block";
o.innerHTML = "Phone number length not valid.";
return false;
}
console.log("Second pass accepted", n.value);
return true;
});