Check if html form numeric field has a maximum of 6 numbers with PHP

4

I need to test if field is filled and if it is composed of up to 6 numbers using the PHP language

    
asked by anonymous 07.05.2018 / 19:10

3 answers

7

You can check if a field is populated in several ways:

if($campo != NULL )
if(!$campo)
if(!$campo == "")
if(isset($campo))
if(!empty($campo))
if(strlen($campo) > 0) 
if(!strlen($campo)) // porque esta função retorna zero caso o $campo esteja vazio

The ! serves to deny an operation, "evaluates" the inverse of what follows.

To verify that $campo contains a maximum of 6 numbers, you can use strlen as before:

if(strlen($campo)<=6 && strlen($campo))

Now you should use the one that best fits your needs.

  

References:
NULL
isset
empty strlen

    
07.05.2018 / 19:29
3

In addition to the other answers, they are correct. I believe you want to evaluate if the field is filled up to 6 NUMBERS . I created two options:

Option 1

You can use is_numeric :

It will return true if the string is a numeric string, and along with strlen of the other answers you will get what you want:

$numeros = trim($_POST['numero_de_registro']);

if(is_numeric($numeros) && $numeros != "" && strlen($numeros) <= 6){
    echo "Está tudo certo aqui -> ".$numeros;
}

Return examples of is_numeric :

"123a" -> false
"123"  -> true
" 123" -> true
"1a2"  -> false

Option 2

Using preg_match

The preg_match will return 1 if the evaluation is correct. That is, if there are 6 digits in this string:

$numeros = trim($_POST['numero_de_registro']);
if(preg_match("/\d{1,6}/", $numeros)){
    echo "Está tudo certo aqui -> ".$numeros;
}

Understanding the acronym:

\d    -> dígitos [0-9]
{1,6} -> quantidade dígitos que devem existir nessa avaliação, no mínimo 1 e no máximo 6

If you do not want 0 , you can change it to this:

preg_match("/[1-9]{1,6}/", $numeros);
    
07.05.2018 / 21:36
2

Using php you use the strlen() function, which counts the number of characters in the string:

$str=strlen($_POST['sua_variável']);
if($str==6){echo 'ok';}
    
07.05.2018 / 19:22