Print an enabled message on the screen after a validation

Asked

Viewed 38 times

0

I did a validation of email and Cpf to see if they are already registered, is there a better way to write the message in the variable $menssage? Than to do the validation one by one?

if($emailRetornado !== null || $cpfRetornado !== null){
    if($emailRetornado !== null && $cpfRetornado !== null){
        $menssage = "EMAIL e CPF já cadastrados!";
    }
    else{
     //Ou o email foi retornado como não valido ou o cpf
         if($emailRetornado !== null){
             $menssage = "EMAIL já cadastrado!";
         }
         if($cpfRetornado !== null){
             $menssage = "CPF já cadastrado!";
         }
     }
}
echo $menssage;

1 answer

1

On the basis that $emailRetornado and $cpfRetornado comes from the database or is there already a previous record of this person.

Change the logic to identify which of the fields already has some value, with a simple if for each, use empty() to check if value in the variables. $erros is an array that has messages of errors that have occurred, so if it is empty the person’s registration does not yet exist, otherwise cancel the process and display the error message with a implode() for example.

$emailRetornado = '[email protected]';
$cpfRetornado =  '';

$erros = [];
if(!empty($emailRetornado)) $erros[] = 'EMAIL já cadastrado!';
if(!empty($cpfRetornado)) $erros[] = 'CPF já cadastrado!';

if(!empty($erros)){
    echo 'Problemas no cadastros <br>'. implode('<br>', $erros);
} else {
    //faça o tratamento do fluxo de sucesso aqui<<
}

Example - ideone

Browser other questions tagged

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