Showing validation errors in the contact form

Asked

Viewed 212 times

3

I have this contact form and I would like to be shown all validation errors when you have, for example, if you leave the field name and email without filling, when you gave Ubmit return these two errors, in the current code only shows an error, even if you have others, I’ve searched several codes on the internet and I couldn’t solve it, someone can help me?

css style.

*,
*:before,
*:after {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
body {
  font-size: 14px;
  background: #F7F7F7;
  color: #333;
}
.clear {
  clear: both;
}
.container {
  max-width: 700px;
  margin: 0 auto;
}
h1 {
  color: #333;
  text-align: center;
}
p {
  font-size: 16px;
  text-align: center;
}
.formulario {
  border: solid 1px #ccc;
  padding: 20px;
  border-radius: 5px;
  width: 100%;
  float: left;
}
input:focus::-webkit-input-placeholder {
  color: transparent;
}
input:focus:-moz-placeholder {
  color: transparent;
}
/* FF 4-18 */

input:focus::-moz-placeholder {
  color: transparent;
}
/* FF 19+ */

input:focus:-ms-input-placeholder {
  color: transparent;
}
/* IE 10+ */

textarea:focus::-webkit-input-placeholder {
  color: transparent;
}
textarea:focus:-moz-placeholder {
  color: transparent;
}
/* FF 4-18 */

textarea:focus::-moz-placeholder {
  color: transparent;
}
/* FF 19+ */

textarea:focus:-ms-input-placeholder {
  color: transparent;
}
/* IE 10+ */

.nome,
.email,
.telefone,
.assunto {
  height: 50px;
  width: 100%;
  float: left;
  padding: 0px 10px;
  margin-bottom: 20px;
  font-size: 20px;
  border: solid 1px #ccc;
  border-radius: 3px;
  color: #777;
}
.email,
.assunto {
  float: right;
}
.formulario .mensagem {
  border: solid 1px #ccc;
  width: 100%;
  height: 150px;
  float: left;
  font-size: 16px;
  color: #777;
  margin-bottom: 20px;
  border-radius: 3px;
  padding: 10px;
}
.formulario .enviar {
  background: #58D68D;
  color: #fff;
  text-transform: uppercase;
  border: none;
  cursor: pointer;
  text-align: center;
  padding: 15px 0px;
  width: 100%;
  font-size: 18px;
  border-radius: 3px;
}
.formulario .enviar:hover {
  background: #2ECC71;
}

index.html

<div class="container">
  <form class="formulario" action="enviar.php" method="POST">
    <input class="nome" type="text" name="nome" placeholder="Nome" />
    <input class="email" type="text" name="email" placeholder="E-Mail" />
    <input class="telefone" type="text" name="telefone" placeholder="Telefone" />
    <input class="assunto" type="text" name="assunto" placeholder="Assunto" />
    <textarea class="mensagem" name="mensagem" placeholder="Digite sua mensagem"></textarea>
    <input class="enviar" name="enviar_email" type="submit" value="Enviar Dados" />
  </form>
  <div class="clear"></div>
</div>

send php.

require_once 'phpmailer/class.phpmailer.php';
require_once 'phpmailer/class.smtp.php';
if (isset($_POST['enviar_email'])):
$nome = strip_tags(trim($_POST['nome']));
$email = strip_tags(trim($_POST['email']));
$telefone = strip_tags(trim($_POST['telefone']));
$assunto = strip_tags(trim($_POST['assunto']));
$mensagem = strip_tags(trim($_POST['mensagem']));
$erro = array();
if (empty($nome)):
    $erro[] = "Digite seu nome";
elseif (empty($email)):
    $erro[] = "Digite um email";
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)):
    $erro[] = "E-Mail invalido";
elseif (empty($telefone)):
    $erro[] = "Digite seu telefone";
elseif (empty($assunto)):
    $erro[] = "Digite um assunto";
elseif (empty($mensagem)):
    $erro[] = "Digite uma mensagem";
else:
    $Email = new PHPMailer();
    $Email->setLanguage('br');

    $host = '';
    $username = '';
    $senha = '';
    $porta = '';
    $secure = '';

    $receber_email = '[email protected]';
    $receber_nome = 'Sérgio Machado';

    $from = $username;
    $fromName = 'Sérgio';

    $Email->isSMTP();
    $Email->Host = $host;
    $Email->SMTPAuth = true;
    $Email->Username = $username;
    $Email->Password = $senha;
    $Email->Port = $porta;
    $Email->SMTPSecure = $secure;

    $Email->From = $from;
    $Email->FromName = $fromName;
    $Email->addReplyTo($email, $nome);
    $Email->addAddress($receber_email, $receber_nome);

    $Email->isHTML(true);
    $Email->CharSet = 'utf-8';
    $Email->WordWrap = 70;

    $Email->Subject = $assunto; //Assunto
    $Email->Body = $mensagem;

    $enviado = $Email->send();
    if ($enviado) {
        echo 'E-mail enviado com sucesso';
    } else {
        echo 'Error: ' . $Email->ErrorInfo;
    }
endif;
endif;

foreach ($erro as $err) {
if (!empty($err)):
    echo $err;
endif;
}
?>

  • Opa @Miguel solved yes man, I do not know what happened, I marked again, thank you very much, now I put the ajax and got mass, but to see some people below say that it is not recommended to use so many ifs

  • Don’t worry, it doesn’t matter and it doesn’t hurt to use the if you need it.... The only thing about using 9999 ifs is that the code gets very extensive... Otherwise, if they are well structured, there is nothing else. However feel free to choose any one solutions below

  • I understood perfectly @Miguel, a very simple thing that solved my problem, I think this collaboration of people in helping each other. in that same form I added the image field and whenever I give Submit returns a PHP error I do not if it is the ajax that is interfering.

  • Without seeing I do not know. The best thing to do is to ask another question with relevant code and explain the problem. I and other colleagues try to help you.

1 answer

5


The problem is in the conditions, as they are wrapped in else if(... from the moment you enter one you will no longer enter the next, even if it is true. Do so:

$erro = array();
if (empty($nome)) {
    $erro[] = "Digite seu nome";
}
if (empty($email)){
    $erro[] = "Digite um email";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $erro[] = "E-Mail invalido";
}
if (empty($telefone)) {
    $erro[] = "Digite seu telefone";
}
if (empty($assunto)) {
    $erro[] = "Digite um assunto";
}
if (empty($mensagem)) {
    $erro[] = "Digite uma mensagem";
}
if(count($erro) < 1) {
    // Mandar email, está tudo bem, não há nada no array $erro
}
else {
    foreach ($erro as $err) {
        echo $err. '<br>';
    }
}

Another way to do:

if (isset($_POST['enviar_email'])) {

    $required = array( // as keys têm de ser as mesmas do array $_POST
        'nome' => 'Digite seu nome',
        'telefone' => 'Digite seu telefone',
        'assunto' => 'Digite um assun',
        'mensagem' => 'Digite uma mensagem'
    );

    $erro = array();
    $inputs = array();
    foreach($required as $key => $err_msg) {
        if(empty($_POST[$key])) {
            $erro[] = $err_msg;
        }
        else {
            $inputs[$key] = strip_tags(trim($_POST[$key]));
        }
    }
    if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { // isto só por si já verifica se o email está vazio, e se é valido (não vale a pena strip_tags, trim)
        $erro[] = "E-Mail invalido";
    }
    if(count($erro) > 0) {
        foreach ($erro as $err) {
            echo $err. '<br>';
        }
    }

    else {

        // envio de email, alterar estes campos:
        $Email->addReplyTo($_POST['email'], $inputs['nome']);
        $Email->Subject = $inputs['assunto'];
        $Email->Body = $inputs['mensagem'];
    }
}
  • may even work, but it’s not recommended to use as many ifs as this... you don’t think?

  • 2

    Why not? You could make one foreach(.. to go through the inputs and see if they are empty, in this case the only one that differs is the email... But note that you were going to do exactly the same number of checks... In other words, in terms of performance it was the same, and in terms of readability and adequacy to the code of the colleague this solution seems to me appropriate... And remember that there is a customised message for each input that it is empty, there was not much back to give in this case.... The only windage would even be the reduction of code lines at the cost of readability for the colleague who asked the question

  • I won’t complain, now if there’s a better way to do it!

  • 2

    It’s no better to go through the trouble of putting inputs into the array on the other hand. But I will. Keep in mind that it’s not better. It’s just different

  • Written by @Paulohenriqueneryoliveira, here’s another way to do it

  • if there’s another way to do it, yes! even because PHP allows you to do it in several ways, but you’ve already put it in two ways so I think enough, I’ll do it in a simpler way and I owe you an answer... ok?!

  • I wasn’t asking if there was, I was saying there’s another way up there. With the same functionality exactly. I also want to know, I’m always willing to learn. Obgado. Of course there are endless ways to do @Paulohenriqueneryoliveira, I know perfectly that I don’t have exclusivity in the ways to make validations in Forms, lol each makes it their own way, a better other worse, a different other equal

  • Yes now that I understand, and you’re from Portugal? I saw by the Portuguese "there is another way of doing it" I understood if there was another way of doing it -> that was the confusion in the language only this!

  • Yes I am, no problem @Paulohenriqueneryoliveira

Show 4 more comments

Browser other questions tagged

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