PHP numeric field validation

1

I have the following function:

function valida_valor2($str)
{
    $count = strlen($str);

    if (($count > 19) OR (!is_numeric($str))) {
        return "INVALIDO";
    }else {
        return $str;
    }
}

When I call it in my code it returns INVALIDO in the following call: Since the variables $valor_iem9... = 0;

if ((valida_valor2($valor_iem9_f_a) == 'INVALIDO') || (valida_valor2($valor_iem9_f_b) == 'INVALIDO') || (valida_valor2($valor_iem9_f_c) == 'INVALIDO') || (valida_valor2($valor_iem9_f_d) == 'INVALIDO') || (valida_valor2($valor_iem9_f_e) == 'INVALIDO')) {
    echo "Campo IEM9 Pessoa Física inválido";
    exit;
}

Any light?

    
asked by anonymous 01.11.2017 / 12:23

2 answers

1

To validate if input (string) contain only digits use the function ctype_digit() .

You can simplify the logic by joining these variables into an array and then apply the valida_valor2() function to each element with array_filter() in the callback compare if the value returned is INVALID.

Finally check that the sum of invalid elements is greater than or equal to one.

function valida_valor2($str){
    $count = strlen($str);

    if (!ctype_digit("$str") || $count > 19) {
        return "INVALIDO";
    } else {
        return $str;
    }
}

//junta as variáveis em um array
$arr = array(
    $iem9_f_a = str_repeat(1, 5),
    $iem9_f_b = str_repeat(2, 19),
    $iem9_f_c = str_repeat(2, 19),
    $iem9_f_d = '123abc',
    $iem9_f_e =  1.99
);


$validacao = array_filter($arr, function($item){ return valida_valor2($item) == 'INVALIDO';});


if(array_sum($validacao)){
    echo 'existem erros <pre>';
    print_r($validacao);
}else{
    echo 'OK';
}
    
01.11.2017 / 12:34
0

Try something like this:

function valida_valor2($str)
{
    $count = strlen($str);

    if (($count > 19) OR (!is_numeric($str))) {
        return "INVALIDO";
    } else {
        return $str;
    }
}

if ((valida_valor2(strval($valor_iem9_f_a)) == 'INVALIDO')) {
    echo "Campo IEM9 Pessoa Física inválido";
    exit;
}
    
01.11.2017 / 12:44