I have searched and looked at different contact form examples and topics about displaying error message via Array without any success.
Now my question is?
Is there a way to include another variable in $errors
or a array
to distribute the error messages to each specific field to display the error messages below or to the side of each failed form field.
My form:
<!DOCTYPE html>
<html>
<head>
<title>Formulario de Contacto</title>
</head>
<body>
<?php
session_start();
$errors = '';
$nombre = '';
$email = '';
$seleccionado = '';
$telefono = '';
$mensaje = '';
if(isset($_POST['submit'])) {
if($_SESSION['vcode'] != $_POST['vcode']) {
$errors .= "Los caracteres no coincide con el código captcha";
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$nombre = test($_POST["name"]);
$email = test($_POST["mail"]);
$telefono = test($_POST["phone"]);
$mensaje = test($_POST["message"]);
$seleccionado = test($_POST['producto']);
}
if(empty($nombre)) {
$errors .= "\n Por favor ingrese su nombre.";
}else {
if (!preg_match("/^[a-zA-Z ]*$/",$nombre)) {
$errors .= "\n Sólo se permiten letras y espacios en blanco.";
}
}
if(empty($email)) {
$errors .= "\n Por favor ingrese su email. ";
}else{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .="\n email no valido";
}
}
if(empty($telefono)) {
$errors .= "\n Por favor ingresar su número telefono. ";
}else{
if(!preg_match("/^\+?\d{1,3}?[- .]?\(?(?:\d{2,3})\)?[- .]?\d\d\d[- .]?\d\d\d\d$/", $telefono)) {
$errors .="\n Número no valido";
}
}
if($_POST['producto'] == 0){
$errors .= "\n Debe seleccionar un producto";
}
if(empty($mensaje)) {
$errors .= "\n Por favor ingrese su mensaje. ";
}
if(empty($errors)) {
$asunto = "";
$message = "Usuario:".$_POST['name']." Email:".$_POST['mail']." Telefono ".$_POST['phone']." Informacion ".$_POST['message'];
$destino = "[email protected]";
$remitente = "From: [email protected]";
mail($destino,$asunto,$message,$remitente);
unset($_POST['submit']);
$msg= "Gracias por sus comentarios";
}
}
?>
<?php
function test($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="error">
<?php
if(isset($msg)){
echo "<p class='err'>".$msg."</p>";
}else{
if (isset($errors))
echo "<p class='err'>".nl2br($errors)."</p>";
# code...
?>
</div>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" autocomplete="off" enctype="multipart/form-data">
<div class="touch">
<div class="name">
<input type="text" name="name" placeholder="Name" value='<?php echo htmlentities($nombre) ?>'>
</div>
<div class="email">
<input type="text" name="mail" placeholder="Email" value='<?php echo htmlentities($email) ?>'>
</div>
<div class="phone">
<input type="tel" name="phone" placeholder="Phone" value='<?php echo htmlentities($telefono) ?>'>
</div>
<div class="select-pro">
<select name="producto">
<?php
$datos = array("Asunto","TV","Internet");
for($i=0; $i<count($datos); $i++) {
if($i==$seleccionado) {
echo "<option value='".$i."' selected>".$datos[$i]."</option>";
}else {
echo "<option value='".$i."'>".$datos[$i]."</option>";
}
}
?>
</select>
</div>
<div class="Customer-message">
<textarea id="message" name="message" placeholder="Su consulta..."><?php echo htmlentities($mensaje) ?></textarea>
</div>
<div class="capcha">
<img src="image.php" name="vcode" id="phoca-captcha"/>
<input name="vcode" type="text" placeholder="Codigo captcha">
</div>
<input type="submit" name="submit" value="Enviar">
</div>
</form>
<?php } ?>
</body>
</html>
I'm going to leave you an example tested in
localhost
.To start with, I've changed the statements
if
else
if
toif
,elseif
else
, I think it looks cleaner and better structured.To launch the all correct message, we simply check that all
variables
of the form are created correctly. Otherwise, it will launch, depending on the case, the error messages for eachinput
incorrectly filled out or empty.It's a simple system, you could always advance by
jQuery
,AJAX
,PHP
, or you could even quickly create a little animationCSS3
if you have little knowledge, and it shows those error messages for a specific time.I have also optimized the code a bit
PHP
.I have added to the Captcha rule, the case if it is empty, it was simply adding our statements
if
elseif
else
. You could add the ones you want, if you need to do more checks it could be something like thisif
elseif
elseif
….else
(an example would be adding another check to count the minimum or maximum of a string, etc.).To the errors I have added a
span
with attributeclass
to create a standard rule for such messages, in this case a small animation with an easy time to modify (7 seconds), the animation has a small effect at its beginning and end.CSS example :
HTML example :
Luck!
What occurs to me is something like this, obviously this is without
style
but you can print them inside one<span>
or one<p>
and give it classes so that it can see well below or to the side.It depends on how you want the response, whether immediately while you jump from one textform to another or after sending with submit
In the first case you have to rely on Jscript, in the second with a global variable ($_session[]) that is set according to the error