How to validate phone in php

3

I'm trying to validate my phone number, both landline and cell phone, and I'm trying to do that, no matter how the user types:

11965453789

(11) 965453789

(11) 965453789

(11) 96545-3789

Always save in the database and show back to the user in this format: (11) 965453789.

How do I do this in php?

    
asked by anonymous 03.08.2016 / 23:00

5 answers

5

I use this function to validate phone:

function celular($telefone){
    $telefone= trim(str_replace('/', '', str_replace(' ', '', str_replace('-', '', str_replace(')', '', str_replace('(', '', $telefone))))));

    $regexTelefone = "^[0-9]{11}$";

    //$regexCel = '/[0-9]{2}[6789][0-9]{3,4}[0-9]{4}/'; // Regex para validar somente celular
    if (preg_match($regexCel, $telefone)) {
        return true;
    }else{
        return false;
    }
}
    
03.08.2016 / 23:21
6

I think you need a regex like this: /\(?\d{2}\)?\s?\d{5}\-?\d{4}/

Example: link

In this regex:

  • \ is to escape some special characters that without this \ have other functionality. Escape with \ is the same character.
  • ? means optional, there may or may not be.
  • {n} means "the previous character" exactly n times.

You can still use ^ at start and $ at the end to ensure there is nothing resp. before or after. In this case the regex would be /^\(?\d{2}\)?\s?\d{5}\-?\d{4}$/ .

To apply this regex in PHP you can do this:

if(preg_match("/\(?\d{2}\)?\s?\d{5}\-?\d{4}/", $phone)) {
  // o telefone é válido
}
    
03.08.2016 / 23:08
2

If you want to let the user enter the number freely and apply sanitization:

// número que o usuário digitou
$n = '(11) 456-456-4567';

// faz um cast para o tipo numérico inteiro.
// isso quer dizer que tudo que não for numérico, incluindo pontos, será removido.
$n = (int)$n;

//mostra resultado da sanitização
echo $n;
//output 114564564567

Once you have done this, simply save it to the database or any other location you wish.

At the time of viewing you can apply some mask, preferably using JavaScript.

Validation

As for the validation, you can check for the size of the string.

This will also depend on how you receive the data. For example, if you receive the area code separate from the number, it makes the validation a bit easier.

Cell phones have 11 digits, usually. So a validation could be done like this

if (strlen($n) == 11) {
    // provavelmente é número mobile
}

Mask

Example of ge mask in PHP link

Generic JavaScript mask example link

Particularly I prefer this freer way because the user gets annoyed with masks and validations that do not tolerate data entry with sanitization.

Auto formatting while typing

Masks, especially when applied in runtime, auto formatting at the time you type, often ends up disrupting the user's experience of using the site. Worse still when the mask has some bug that prevents the user from completing a form and this is very common. on many websites.

Advantage

The solution proposed above aims at reusing codes.

The subject here is specific about phone numbers, however, you can apply this same routine to several other types like ZIP, CPF, CNPJ, serial numbers, any type of number with any type of formatting.

    
04.08.2016 / 16:41
1

After having consulted this page and started to scratch a gambiarra, I noticed that I had in the "chest" a ready function ... And looking up I notice that the foundation was already given here by @DanielOmine, remembering that cellular with DDD has 11 digits and fixed 10 digits. PS: no DDD are 9 and 8 respectively.

It was around the year 2000 that Brazilian phones had 8 digits, and between 2010 and 2013, all cell phones were 9 digits. See Anatel standards .

The generic algorithm for interpreting a supposed free-phone string is based on the Anatel rule ... It's only a little more complicated because it needs to check the context and know how to differentiate between cases with and without DDI and DDD. >

Anyone interested in ... Algorithm that "sanitizes" typed telephone data, written (in PL / SQL) and validated years ago ... I update if I find something better later (leaving it in Wiki for you to edit) .

CREATE or replace FUNCTION lib.get_string_tel(text) RETURNS text AS $f$
  SELECT regexp_replace(
      $1
      ,'^.*?((\+?55[\s-]|\+\d\d[\s-])?\s*\(?\d\d\)?[\s\-\.]*\d[\.\s]?\d\d[\d\s\.\-]+).*?$'
      ,''
    )
$f$ LANGUAGE SQL IMMUTABLE;
CREATE or replace FUNCTION lib.telbr_split(
  p_tel text  -- a string contendo o telefone 
  ,p_pode_ddi boolean DEFAULT true -- deixa preceder 55?
  ,p_ddd_default text DEFAULT '11' -- contexto Sampa
  ,p_max int DEFAULT 21  -- tamaho  máximo da string para remover outros dígitos
) RETURNS text[] AS $f$
DECLARE
  basenum text;
  digits text;
  len int;
  ret text[];
BEGIN
  basenum := trim(p_tel);
  IF length(basenum)>p_max THEN
    basenum := lib.get_string_tel(basenum);
  END IF;
  digits := lib.digits(basenum);
  IF p_pode_ddi THEN
    IF length(digits)>=14 THEN
      basenum := regexp_replace(basenum,'^[^\d]*\d\d','');
      digits := lib.digits(basenum);
    ELSEIF length(digits)>=12 AND substr(digits,1,2)='55' THEN
      basenum := regexp_replace(basenum,'^[^\d]*55','');
      digits := lib.digits(basenum);
    END IF;
  END IF;
  digits := regexp_replace(digits,'^0+','');
  len := length(digits);
  IF len<=9 THEN
    digits := p_ddd_default||digits;
  END IF;
  RETURN array[substr(digits,1,2), substr(digits,3)];
END
$f$ LANGUAGE PLpgSQL IMMUTABLE;

The first function extracts the string containing apparently a phone number in the middle of free text.
For example, another day was entered as Iphone 6s plus (11) 9 1234-5678 as one of those Google forms.

The second is that it actually normalizes and explodes the two-part number, DDD and number.

The PL / SQL language (PostgreSQL or Oracle databases) is almost a Pascal, very easy to convert to PHP, Javascript, etc. Just be patient.

    
26.02.2018 / 16:59
0

Use this code that uses preg_match to validate and preg_replace to fix.

$validacao = "^\(?(\d{2})\)?\b+(\d{5})\-?(\d{4})$";
if (preg_match($validacao, $telefone)){
    $telefone = preg_replace($validacao, "($1)$2$3", $telefone);
} else {
    //Acao para erro de validacao
}
    
04.08.2016 / 20:13