Validating php inputs

Asked

Viewed 304 times

3

I need to show all errors in filling out the form first to then run FOR, but if using DIE for each IF will stop the script and will not show if there is any extra error, which way to do this?

if($parcelas == 0){
echo "Digite valor acima de 1 parcela para gerar<br>";
}
if($valor == 0){
echo "Digite valor acima de 0 para gerar<br>";
}
if($vencimento) {
function validateDate($date, $format = 'd-m-Y')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}
if (validateDate($vencimento,'d/m/Y') == false){
    echo "Digite a data de vencimento corretamente DIA/MÊS/ANO<br>";
    die;
}
}
///Executar o for abaixo
for($i =0, $x = 1 ;$x <= $parcelas, $i <= $parcelas; $x++ ,$i++ ){}
  • 3

    Don’t do this on the server side, do it on the client side. It’s faster, using jQuery or Javascript. Or it needs to be on the server side ?

  • 1

    On hand? I can’t even remember how to do it in PHP ;)

  • there is more practical way @Wallacemaxters ?

  • More practical, taking into account the structured system, would be Edilson’s response

1 answer

2


A simple way to handle situations like this would be to add each error returned to a single array.

<?php

$erros = "";

function vazio($args){
    global $erros;
    if(!empty($args) && is_array($args)){
        foreach($args as $arg){
            if(empty($_POST[$arg])){
                $erros[$arg] = $arg . " nao pode estar vazio";
            }
        }
    }
}
if(isset($_POST)){
    vazio(['nome','email','senha']);
    if($erros){
        print "<strong>Erros encontrados</strong>";
        foreach($erros as $erro){
            print "<li>{$erro}</li>";
        }
    } else {
        print "<strong>Nenhum erro encontrado</strong><br/>";
        print "Ola {$_POST['nome']}";
    }
}

?>

Imagining that the form was something like this:

<form method="POST" action="">
    <input type="text" name="nome">
    <input type="email" name="email">
    <input type="password" name="senha">
    <input type="submit" name="enviar" value="enviar">
</form>

The logic is to log each error returned into a single array, and then check if there is an error in that array if it does not proceed with the script execution.

Browser other questions tagged

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