Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Phone Number Validation

I've am using jQuery validation plugin to validate a mobile phone number and am 2/3 of the way there.

The number must:

  • Not be blank - Done,
  • Be exactly 11 digits - Done,
  • Begin with '07' - HELP!!

The required rule pretty much took care of itself and and I managed to find the field length as a custom method that someone had shared on another site.

Here is the custom field length code. Could anyone please suggest what code to add where to also require it begin with '07'?

$.validator.addMethod("phone", function(phone_number, element) {
var digits = "0123456789";
var phoneNumberDelimiters = "()- ext.";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 11;
s=stripCharsInBag(phone_number,validWorldPhoneChars);
return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
}, "* Your phone number must be 11 digits");

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 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;
}
$(document).ready(function(){
$("#form").validate();
});
like image 240
User787665 Avatar asked Dec 07 '25 03:12

User787665


2 Answers

The code in the question seems a very complicated way to work this out. You can check the length, the prefix and that all characters are digits with a single regex:

if (!/^07\d{9}$/.test(num)) {
   // "Invalid phone number: must have exactly 11 digits and begin with "07";
}

Explanation of /^07\d{9}$/ - beginning of string followed by "07" followed by exactly 9 digits followed by end of string.

If you wanted to put it in a function:

function isValidPhoneNumber(num) {
   return /^07\d{9}$/.test(num);
}

If in future you don't want to test for the prefix you can test just for numeric digits and length with:

/^\d{11}$/
like image 115
nnnnnn Avatar answered Dec 11 '25 16:12

nnnnnn


You could use this function:

function checkFirstDigits(s, check){
    if(s.substring(0,check.length)==check) return true;
    return false;
}

s would be the string, and check would be what you are checking against (i.e. '07').

like image 27
Tim Withers Avatar answered Dec 11 '25 18:12

Tim Withers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!