Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regexp using val().match() method

I'm trying to validate a field named phone_number with this rules:

the first digit should be 3 then another 9 digits so in total 10 number example: 3216549874

or can be 7 numbers 1234567

here i have my code:

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

Why doesnt work :( when i put that into an online regexp checker shows good.

like image 890
alexistkd Avatar asked Dec 22 '11 15:12

alexistkd


People also ask

What does match() return in JavaScript?

The match() method returns an array with the matches. The match() method returns null if no match is found.

How do you evaluate a regular expression in JavaScript?

JavaScript | RegExp test() Method The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false. Where str is the string to be searched.

What is the use of match in JavaScript?

match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array.

What is G in regex?

The g flag indicates that the regular expression should be tested against all possible matches in a string.


1 Answers

You should be using test instead of match and here's the proper code:

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

Match will find all the occurrences, while test will only check to see if at least one is available (thus validating your number).

like image 74
alessioalex Avatar answered Oct 07 '22 22:10

alessioalex