PHP - how to use placeholders for form validation messages

Asked

Viewed 350 times

-3

Hello, I am using placeholders to send error and successful form submission messages within the inputs themselves. Placeholders are gray. When the form is sent, if there is an error, the error msg appears through the placeholder in red. Message exchange is working, but the CSS style of placeholders is not.

My code has PHP in the header where I style placeholders in gray first. Then, below, in body, another PHP code validates the form. I think it is PHP in the header that is creating the error, possibly wrong in the scope of the variables. It is because the two parts of the code are separate?

Can you give me a hand?

No header:

<?php
   $phname = 'Please, inform your name...';
   $phemail = '...and e-mail';
   $styleName = '.namecolor::-webkit-input-placeholder {color:blue}';
   $styleEmail = '.emailcolor::-webkit-input-placeholder {color:inherit}';
   $phstyle = '<style>'.$styleName.$styleEmail.'</style>';

  echo $phstyle;
?>

Comes the body and then:

<?php //PHP FOR CONTACT     FORM===============================================================
    if(!empty($_POST['bt-submit'])) {                   
        function test_input($data) {
          $data = trim($data);
          $data = stripslashes($data);
          $data = htmlspecialchars($data);
          return $data;
        }

        $destino = "[email protected]";
        $assunto = "Msg from Decoranno website";                        
        $msgErr = "";
        $nome = $de = $mensagem = "";
        $erro = FALSE;

        if ($_SERVER["REQUEST_METHOD"] == "POST")
        {

          if (empty($_POST["txtnome"]))
            {$phname = 'Please inform your name';
            $erro = TRUE;
            $styleName = '.namecolor::-webkit-input-placeholder {color:red}';
            }
          else
            {$nome = test_input($_POST["txtnome"]);
            if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
                $phname = 'Use only characters and white spaces';
                $_POST['txtnome'] = "";
                $erro = TRUE;
                $styleName = '.namecolor::-webkit-input-placeholder {color:red}';
            }
        }

      if (empty($_POST["txtdest"]))
        {$phemail = 'Please inform your email address';
        $erro = TRUE;
        $styleEmail = '.emailcolor::-webkit-input-placeholder {color:inherit}';
        }
      else
        {$de = test_input($_POST["txtdest"]);
         if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$de)){
             $phemail = 'Sorry, invalid email address';
             $_POST['txtdest'] = "";
             $erro = TRUE;
             $styleEmail = '.emailcolor::-webkit-input-placeholder {color:inherit}';
             }
        }

      if (empty($_POST["txtmsg"]))
        {$msgErr = "Please type your message";
        $erro = TRUE;
        }
      else
        {
            $mensagem = htmlspecialchars_decode(test_input($_POST["txtmsg"]));
            $msgErr = $_POST["txtmsg"]; //Repeat the message already written by the user in case of retry.
        }


        if( $erro == FALSE ){
            if (PATH_SEPARATOR ==":") {
            $quebra = "\r\n";
            } else {
                $quebra = "\n";
                }
            $msgcompleta = "From: ".$nome."<".$de.">".$quebra.$quebra.$mensagem;
            $headers = "MIME-Version: 1.1".$quebra;
            $headers .= "Content-type: text/plain; charset=iso-8859-1".$quebra;
            $headers .= "From: ".$de.$quebra; //E-mail do remetente
            $headers .= "Return-Path: ".$de.$quebra; //E-mail do remetente
            mail($destino, $assunto, $msgcompleta, $headers, "-r". "[email protected]");
            //print "Message successfully sent. Thank you." and reset placeholders on email and name inputs to blank
            $_POST['txtnome'] = $_POST['txtdest'] = $_POST['txtmsg'] = ''; $phname = $phemail = ''; // lets pretend nothing was posted
            $msgErr = 'Message sucessfully sent. Thank you.';
            }
    }
  }
//END OF PHP FOR CONTACT FORM=================================================?>

            <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                <span>Name</span><input class="text-input namecolor" name="txtnome" type="text" value="<?php echo $_POST['txtnome']; ?>" placeholder="<?php echo $phname; ?>" />
                <span>Email</span><input class="text-input emailcolor" name="txtdest" type="text" value="<?php echo $_POST['txtdest']; ?>" placeholder="<?php echo $phemail; ?>" />
                <textarea name="txtmsg msgcolor" placeholder="We are looking forward to hearing from you"><?php echo $msgErr;?></textarea>
                <input id="bt-send" name="bt-submit" type="submit" value="Send your message" />
            </form>
  • 2

    I do not believe that the placeholder exists for this purpose, it is only a hint for user and not a message itself. Take a look at in that doc.

  • True, but in this matter of the message it worked so well that I liked the idea of using. Just the style that is not working. I’ll take a look at the document you suggested. Thank you!

  • And how would you show the message in an already filled field (if the completion was incorrect) ?

  • Fields already filled correctly remain filled after Submit, only the wrong ones are deleted. But now that I have read that document you submitted, the problem is that the placeholder may not appear to the user. So I think I’d better switch to label and span anyway. Still, I’m interested to know why the message isn’t styling.

2 answers

0

php is a structured language. If at the top you define a value and below defines another, the latter will prevail CASE THE LATTER, is actually written. Check whether the $_POST["txtdest"] variable is actually empty. Instead of using and function empty() make conditions of the kind if ($_POST["txtdest"] == '')) for input. Because sometimes the header sends some value in "empty inputs".

    ...

    if ($_POST["txtdest"] == '')
            {$phemail = 'Please inform your email address';
            $erro = TRUE;
            $styleEmail = '.emailcolor::-webkit-input-placeholder {color:inherit}'; //AQUI NÃO DEVERIA SER RED?????
            }
          else
            {$de = test_input($_POST["txtdest"]);
             if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$de)){
                 $phemail = 'Sorry, invalid email address';
                 $_POST['txtdest'] = "";
                 $erro = TRUE;
                 $styleEmail = '.emailcolor::-webkit-input-placeholder {color:inherit}'; //AQUI NÃO DEVERIA SER RED?????
                 }
            }

     ...
  • I did that, that part is quiet, but here’s the thing: the placeholder starts in gray with the phrase "enter your email". If the user leaves blank or puts a wrong email, he should put the "invalid email" message and make the placeholder font red. Everything is working, only the color change that does not :(. I don’t know which part of the code I should change the $Stylename and $Styleemail variable to make it happen

0

Maybe the problem is that the attribute color is not picking because of the bootstrap priority, you can use "! Important" so that no css interferes in the element’s color:

::-webkit-input-placeholder { color:#ff0000!important; }
input:-moz-placeholder { color:#ff0000!important; }

Browser other questions tagged

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