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.
The match() method returns an array with the matches. The match() method returns null if no match is found.
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.
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.
The g flag indicates that the regular expression should be tested against all possible matches in a string.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With