Javascript regexp using val () method. Match ()

I am trying to check a field called phone_number with these rules:

the first digit should be 3, and then another 9 digits, so a total of 10 numeric examples: 3216549874

or maybe 7 numbers 1234567

here i have the code:

        if (!($("#" + val["htmlId"]).val().match(/^3\d{9}|\d{7}/)))
            missing = true;

Why it doesn’t work :( When I put this in the online regex check, it shows well.

+5
source share
4 answers

You should use a test instead of a match, and here is the correct code:

.test(/^(3\d{9}|\d{7})$/)

Match will find all occurrences, while the test will only be checked for the presence of at least one of them (thus checking your number).

+6
source

.

if (!($("#" + val["htmlId"]).val().match(/^3\d{9}/|/\d{7}/)))
            missing = true;

http://jsfiddle.net/alfabravoteam/e6jKs/

+2

I had a similar problem and decided to write it like this:

if (/^(3\d{9}|\d{7})$/.test($("#" + val["htmlId"]).val()) == false) {
    missing = true;
}
+2
source

Try it, it's a little more strict.

.match(/^(3\d{9}|\d{7})$/)
+1
source

All Articles