How to create a regular expression to validate only cell phone number?

Asked

Viewed 766 times

3

I made that expression, but I don’t know if it’s in today’s standards

 "/^[1-9]{2}\s?9\s?\d{8}$/"
  • 3

    https://answall.com/a/144363/30045

  • 1

    Would it really have to be regular expression? I think it would be more efficient to put a mask on the field with jQuery.

  • //$regexCel = '/[0-9]{2}[6789][0-9]{3,4}[0-9]{4}/'; https://answall.com/questions/144362/como-validar-phone-em-php

2 answers

2

Regarding the question, I think you should be a little more specific, its title does not match the description of the question.

Responding to the title:
You can create a regex that reads the digits separately and only match if the number has 8 to 9 digits with 2 additional to indicate DDD.
So you can wear something like this:

(\({0,1}\d{0,2}\){0,1} {0,1})(\d{4,5}) {0,1}-{0,1}(\d{4})

This regex identifies whether there are separators like space, "-" and "()", since they are not mandatory attributes it only considers that they can exist and capture in the same way, here is a example of how it works.

Answering the description of the question:
Your regex still works, it’s in today’s standards, but I wouldn’t use it for not considering the possible separators that might exist in the phone fields, being stuck to possibilities that should be at the beginning of lines and accepting line breaks, tabs and spaces between specific parts that may end up capturing strings of characters that should not be captured.

0

Hmmm maybe this expression will do, it worked for some tests with 9 digits and 8 digits, with or without ddd, and with or without hifen

var cel = /[0-9]{0,2}?[9]?[0-9]{4}-?[0-9]{4}/;
cel.test('91234-5678') // true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.