How to check If a Tel: area code is correct using jquery?
Hy I need to check if the given phone area code is correct. i created a input field, user can insert a tel area code like 0044 oder 0090 and so on. I restricted the input field to 4 chars. I need to check after the 4 chars are entered if the area code is correct.
What it 开发者_Go百科should do.
After entering 4 number, the script should check the following things.
Does the entered number equals something like "00{number 2 digit only}"
if it doesnt alert("please enter correct tel areacode");
I hope i could explain my problem clear. How can i do it with javascript or jquery?
Is "0000" a valid area code? It has "00" followed by two digits... but I assume the codes are 00 then a number 10 or higher.
$('input.phone').keyup( function(){
var num = $(this).val(), i = parseInt(num, 10), valid = true;
if(num.length==4 && (i<9 || i>99) ){
//phone number is invalid
}
});
But I think that blur event will be more useful here, because the above function wouldn't notify the user if he typed only three digits. Notification will appear as soon as the focus is moved aout of the input box, not as soon as the fourth digit was typed. So my proposition is:
$('input.phone').blur( function(){
var num = $(this).val(), i = parseInt(num, 10), valid = true;
if(num.length != 4 || i<9 || i>99 ){
//phone number is invalid, notify the user
}
});
edit: I thought you're validating some kind of area codes specific to your coutry. If you want to validate international calling codes you may wish to look at this list: http://en.wikipedia.org/wiki/List_of_country_calling_codes - there are many +XXX (or 00XXX) numbers and these won't fit into your 4 characters long input. And many numers aren't in +XX (00XX) format, like +1 (001) for USA. I think you should just check if it's + or 00 followed by at least one digit other than zero and let it in.
/^(\+|00)[1-9]/.test( input.value );
Something like this should work:
$('#field').keyup(function() {
var value = $(this).val();
// Restrict length to 4 characters
if(value.length > 4) {
value = value.substring(0, 3);
$(this).val(value);
}
// Test is value equals to "00{number 2 digit only}"
if(/00\d{2}/.test(value)) {
// Is valid
} else {
// Not valid
}
});
I'd avoid using alert
on the not valid part, as that would give the user an alert box every time he presses a key.
精彩评论