Contact form does not validate and does not send some fields

Asked

Viewed 445 times

3

Hello, it’s my first question here! The problem is this... I took a form on the net and tried to adapt to my needs, but the fields I created ($phone and $empresa) do not want to validate, I had to remove the validation of these fields, the form sent but these fields arrive blank I am mto Noob in everything, mainly php :'(


This is the form with the buged validation x_x

o formulário


This is how the message arrives, when I remove the validation of $phone and $empresa

como eu recebo o email removendo a validação de phone e empresa


HTML

<form id="contactform" action="chamadotecnico.php" name="contactform" method="post">
  <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
    <input type="text" name="name" id="name" class="form-control" placeholder="Nome">
    <input type="text" name="phone" id="phone" class="form-control" placeholder="Telefone">
  </div>
  <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
    <input type="text" name="email" id="email" class="form-control" placeholder="E-mail">
    <input type="text" name="empresa" id="empresa" class="form-control" placeholder="Empresa">
  </div>
  <div class="col-lg-12">
    <textarea class="form-control" name="comments" id="comments" rows="6" placeholder="Descrição do problema técnico"></textarea>
    <button type="submit" value="SEND" id="submit" class="btn btn-lg btn-primary pull-right">Enviar</button>
  </div>
</form>

PHP

<?php

if(!$_POST) exit;

// Verificação de endereço de email, não mexa!
function isEmail($email) {
    return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}

if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");

$name     = $_POST['name'];
$email    = $_POST['email'];
$phone    = $_POST['phone'];
$empresa  = $_POST['empresa'];
$comments = $_POST['comments'];

if(trim($name) == '') {
    echo '<div class="error_message">Informe o seu nome.</div>';
    exit();
} else if(trim($email) == '') {
    echo '<div class="error_message">Insira um endereço de e-mail.</div>';
    exit();
} else if(!isEmail($email)) {
    echo '<div class="error_message">Atenção! Você tem digitar um endereço de e-mail inválido, tente novamente.</div>';
    exit();
}

if(trim($phone) == '') {
    echo '<div class="error_message">Informe um telefone para contato.</div>';
    exit();
} else if(trim($empresa) == '') {
    echo '<div class="error_message">Informe o nome da sua empresa.</div>';
    exit();
} else if(trim($comments) == '') {
    echo '<div class="error_message">Informe a descrição do seu problema.</div>';
    exit();
}

if(get_magic_quotes_gpc()) {
    $comments = stripslashes($comments);
}

$address = "[email protected]";
$e_subject = 'Chamado Técnico';

$e_body = "Nome: $name\r\nEmail: $email\r\nTelefone: $phone\r\nEmpresa: $empresa" . PHP_EOL . PHP_EOL;
$e_content = "Descrição do problema:\r\n$comments" . PHP_EOL . PHP_EOL;
$e_reply = "Você pode entrar em contato $name via email, $email ou pelo telefone $phone";

$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );

$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;

if(mail($address, $e_subject, $msg, $headers)) {

    echo "<fieldset>";
    echo "<div id='success_page'>";
    echo "<h1>E-mail enviada com sucesso!</h1>";
    echo "<p>Obrigado <strong>$name</strong>, sua mensagem foi enviada, em breve entraremos em contato.</p>";
    echo "</div>";
    echo "</fieldset>";

} else {

    echo 'ERROR!';

}

[Edit] JS I found after the help of friend Sanction

jQuery(document).ready(function(){

    $('#contactform').submit(function(){

        var action = $(this).attr('action');

        $("#message").slideUp(750,function() {
        $('#message').hide();

        $('#submit')
            .after('<img src="images/ajax-loader.gif" class="loader1" />')
            .attr('disabled','disabled');

        $.post(action, {
            name: $('#name').val(),
            email: $('#email').val(),
            website: $('#website').val(),
            subject: $('#subject').val(),
            comments: $('#comments').val(),
            verify: $('#verify').val()
        },
            function(data){
                document.getElementById('message').innerHTML = data;
                $('#message').slideDown('slow');
                $('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
                $('#submit').removeAttr('disabled');
                if(data.match('success') != null) $('#contactform').slideUp('slow');

            }
        );

        });

        return false;

    });

});
  • 1

    It seems to be correct the code, after setting the variable $phone, give a echo $phone and see the value that returns.

  • 1

    I suggest you use some jQuery plugin to do data validation. This avoids validation being done on the Server side (PHP) and yes on the Client side (Browser, via JS, jQuery). It has the validate.js. http://rickharrison.github.io/validate.js/. This is good because of faster page processing.

  • 1

    @Diegosouza validation exclusively on the client side is not a good idea, validation should also be done on the server because a request by CURL can circumvent validation on the client. I suspect that the problem is that the form is sent by AJAX and the Javascript code is not sending the "custom" fields to PHP, do you have any javascript code on this page? it would be good to add here in question.

2 answers

1


The PHP code seems correct. Everything indicates that your form is sent by AJAX, because:

  • there is a spinner at the bottom of the image
  • the error message is generated by a echo followed by exit and should be included by javascript.

Somewhere on your page there must be something like

jQuery('#contactform').on('submit', function(e){
    // ...
})

If there is any instruction .post() or .ajax() include this code in your question. I believe this function that is not sending the phone and company fields.


You can replace the JSON object passed as the second parameter of $.post() (below) by $(this).serialize(), this way all fields of the form will be sent to PHP. For more information go to .serialize() (in English)

{
    name: $('#name').val(),
    email: $('#email').val(),
    website: $('#website').val(),
    subject: $('#subject').val(),
    comments: $('#comments').val(),
    verify: $('#verify').val()
}
  • REALLY!!! I found a js as you said, it seems that he is even responsible for sending the fields. I’ll run the tests and see if it works now, thank you very much for the tip!!!

0

Try using a strip_tags to remove any possible tag HTML that may have come together:

$phone = (trim(strip_tags($_POST['phone'])));

Browser other questions tagged

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