Zeynab Izadi
Zeynab Izadi

Reputation: 1

Regular Expressions for phone numbers and mobiles doesn'nt work correctly

I have a function for validating telephone and mobile numbers. Here is part of my function:

function IsPhone(){
 var mob = /09[123]\d{8}$/;
    var phn = /0\d{10}$/;
    for (var i = 0; i < edit_rows.length; i++) {
        if (edit_types[i] == 5) {
            var phon_val = document.getElementById('phone1').value;
            if (phon_val != "") {
                if (phon_val.match(mob))
                    return true;
                else if (phon_val.match(phn)) {
                    if ((phon_val).length == 11)
                        return true;
                }
                else {
                    msg_req += "Invalid format";
                    return false;
                }
            }
        }
    }
    return true;
}  

But it accepts all of these:
009153842716
09153842716
001234567890
01234567890
what can I do?

Upvotes: 0

Views: 38

Answers (1)

kaesve
kaesve

Reputation: 276

I think adding a ^ at the beginning of your expression would fix it. Your current query would match strings like 'thisisaninvalidvalue09153842716'. Adding the ^ makes sure you don't start with invalid input.

Upvotes: 1

Related Questions