Foros del Web » Programando para Internet » PHP »

Campos obligatorios

Estas en el tema de Campos obligatorios en el foro de PHP en Foros del Web. Hola gente, necesito que me ayuden con el codigo de html y php de un formulario. lo que busco es que si hay un campo ...
  #1 (permalink)  
Antiguo 21/03/2012, 23:29
 
Fecha de Ingreso: marzo-2012
Mensajes: 1
Antigüedad: 12 años, 1 mes
Puntos: 0
Campos obligatorios

Hola gente, necesito que me ayuden con el codigo de html y php de un formulario.

lo que busco es que si hay un campo vacío, el formulario no se envíe.

Este es el formulario que tengo, quiero saber que modificar para que aparezca
un dialogo tipo pop up indicando que no se pueden dejar los campos vacíos.


HTML:

<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<
title>Fornmulario de Contactos

<
body>
<
h3>Formulario de Contactos
<
form id="form1" name="form1" method="post" action="procesar.php">
<label> Ingrese su nombre <br>
<input id="nombre" name="nombre" type="text">
<br>
</label>
<p>Su dirección Email<br>
<input id="email" name="email" type="text">
</p>
<p>Su Número de teléfono <br>
<input id="teléfono" name="teléfono" type="text">

<p>Tipo de contacto<br>
<label>
<select id="tipo" name="tipo">
<option value="Ventas">Ventas</option>
<option value="Preguntas">Preguntas</option>
<option value="Comentario">Comentario</option>
</select>
</label>
</p>
<p>
<label>Mensaje<br>
<textarea id="mensaje" cols="30" rows="3" name="mensaje"></textarea>
</label>

<p>
<label>
<input name="Submit" value="Enviar Formulario >>" type="submit">
</label>
</p>
<p>Formulario de contactos en PHP<br>
<br>
</p>




-------------------------------------------------------------------------------------------

PHP:

<?php

$para = '[email protected]';
$asunto = $_POST["tipo"]; $mailheader = "From: ".$_POST["email"]."\r\n"; $mailheader .= "Reply-To: ".$_POST["email"]."\r\n"; $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; $MESSAGE_BODY = "Nombre: ".$_POST["nombre"]."<br>"; $MESSAGE_BODY .= "Email: ".$_POST["email"]."<br>"; $MESSAGE_BODY .= "Teléfono: ".$_POST["teléfono"]."<br>"; $MESSAGE_BODY .= "Tipo de contacto: ".$_POST["tipo"]."<br>"; $MESSAGE_BODY .= "Mensaje: ".nl2br($_POST["mensaje"])."<br>"; mail($para, $asunto, $MESSAGE_BODY, $mailheader) or die ("Error al enviar el Formulario !");
header( 'Location: http://www.SuSitio.com/gracias.html' )

  #2 (permalink)  
Antiguo 22/03/2012, 07:12
Avatar de linuxzero  
Fecha de Ingreso: noviembre-2011
Ubicación: Argentina
Mensajes: 778
Antigüedad: 12 años, 5 meses
Puntos: 160
Respuesta: Campos obligatorios

1) Tipo de contacto: Tiene un valor seleccionado por default por como lo programaste, por ende no hace falta validar ese campo que es el combo (a menos que la logica que aplicaste no sea la que deberia)

2) El atributo id y name del campo telefono, no lo utilices con acentos, es una muy mala práctica, todos los nombres de variables y atributos y todo lo que sea de uso interno manejalo sin acentos ni ñ

Podes hacer algo asi:

Código PHP:
Ver original
  1. if ($_POST && strlen($_POST['nombre']) > 0 && strlen($_POST['email']) > 0 && strlen($_POST['telefono']) > 0 && strlen($_POST['mensaje']) > 0) {
  2.  
  3. $asunto = $_POST["tipo"]; $mailheader = "From: ".$_POST["email"]."\r\n"; $mailheader .= "Reply-To: ".$_POST["email"]."\r\n"; $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; $MESSAGE_BODY = "Nombre: ".$_POST["nombre"]."<br>"; $MESSAGE_BODY .= "Email: ".$_POST["email"]."<br>"; $MESSAGE_BODY .= "Teléfono: ".$_POST["teléfono"]."<br>"; $MESSAGE_BODY .= "Tipo de contacto: ".$_POST["tipo"]."<br>"; $MESSAGE_BODY .= "Mensaje: ".nl2br($_POST["mensaje"])."<br>"; mail($para, $asunto, $MESSAGE_BODY, $mailheader) or die ("Error al enviar el Formulario !");
  4. header( 'Location: http://www.SuSitio.com/gracias.html' )
  5.  
  6. }
__________________
Si todo fuera tan sencillo como un symfony cc la vida seria más fácil.
http://phpnico.wordpress.com
  #3 (permalink)  
Antiguo 22/03/2012, 07:50
Avatar de JairLizcano  
Fecha de Ingreso: junio-2008
Ubicación: Santander, Colombia
Mensajes: 608
Antigüedad: 15 años, 10 meses
Puntos: 53
Respuesta: Campos obligatorios

Tu tema está parcialmente solucionado gracias a linuxzero. Pero si realmente quieres solucionarlo en su totalidad y encarar cualquier problema de tipo validación de entrada de datos puedes ir directamente a las Expresiones Regulares:

http://www.mclibre.org/consultar/php...regulares.html
  #4 (permalink)  
Antiguo 22/03/2012, 08:18
Avatar de a_gomez  
Fecha de Ingreso: marzo-2012
Ubicación: /var/www/
Mensajes: 48
Antigüedad: 12 años, 1 mes
Puntos: 2
Respuesta: Campos obligatorios

tambien otr forma de validar con un scrip de java que se coloca en el head mira :


Código Javascript:
Ver original
  1. <script language="javascript">
  2. //Su explorador no soporta java o lo tiene deshabilitado; esta pagina necesita javascript para funcionar correctamente<!--
  3. //Copyright © McAnam.com
  4. // http://www.mcanam.com/articulos/JavaScript.php?id=30
  5.    
  6.     function comprobar_formulario(oFormulario)
  7.     {
  8.        
  9.         // Se comprueba si se pasa bien el objeto formulario
  10.        
  11.         var iExiste = false;
  12.         var iCont = 0;
  13.         var sMensaje = "Por favor rellene todos los campos del formulario, faltan \n";
  14.        
  15.         for (iCont = 0 ; iCont < document.forms.length ; iCont++)
  16.         {
  17.             if (document.forms[iCont] == oFormulario)
  18.                 iExiste = true;
  19.                
  20.         }
  21.        
  22.         // No se ha pasado formulario, intentamos coger el primero del formulario
  23.         if (! iExiste)
  24.         {
  25.             oFormulario = document.forms[0];
  26.             if (! oFormulario)
  27.             {
  28.                 alert("Formulario pasado incorrecto.\nNo se pudo encontrar formulario");
  29.                 return false;  
  30.             }  
  31.         }
  32.        
  33.         // Recorremos los elementos del formulario
  34.        
  35.         for (iCont = 0 ; iCont < oFormulario.elements.length ; iCont++)
  36.         {
  37.             if (oFormulario.elements[iCont].type == "text" || oFormulario.elements[iCont].type == "radio")
  38.             {
  39.                 if (oFormulario.elements[iCont].value.length == 0)
  40.                 {
  41.                     alert("Por favor rellene todos los campos del formulario, falta el campo " + oFormulario.elements[iCont].name);
  42.                     oFormulario.elements[iCont].focus();
  43.                     return false;
  44.                 }
  45.             }
  46.         }
  47.        
  48.         // Si hemos llegado aquí, todos los campos son correctos, enviamos el formulario
  49.        
  50.         oFormulario.submit();
  51.        
  52.     }
  53. //-->
  54. </script>


y este es mi formulario ....


Código HTML:
Ver original
  1. <form name="formulario1" id="formulario1" action="form.php" method="post">
  2.                 <table align="center" width="95%">
  3.                     <tr>
  4.                         <td><b>NOMBRE DE EL ESTABLECIMIENTO:</b> <input type="text" name="establecimiento" size="96%">
  5.                     </tr>
  6.                 </table>
  7.                 <table align="center" width="95%">
  8.                     <tr>
  9.                         <td width="50%"><b>RESPONSABLE: </b> <input type="text" name="responsable" size="45%">
  10.                         <td><b>CEDULA: </b> <input type="text" name="cedula" size="30%">
  11.                     </tr>
  12.                 </table>
  13.                 <table align="center" width="95%">
  14.                     <tr>
  15.                         <td width="50%"><b>DIRECCION:</b> <input type="text" name="direccion" size="45%">
  16.                         <td><b>BARRIO: </b> <input type="text" name="barrio" size="53%">
  17.                     </tr>
  18.                 </table>
  19.                 <table align="center" width="95%">
  20.                     <tr>
  21.                         <td><b>TELEFONO: </b> <input type="text" name="telefono" size="20%">
  22.                         <td><b>CELULAR: </b> <input type="text" name="celular" size="20%">
  23.                         <td><b>EMAIL: </b> <input type="text" name="email" size="50%">
  24.                     </tr>
  25.                 </table>
  26.                 <br>
  27.                 <table align="center" width="95%">
  28.                     <tr>
  29.                         <td><b>ACTIVIDAD:</b>
  30.                     </tr>
  31.                    
  32.                     <tr>
  33.                         <td><input type="radio" name="actividad" value="alimetos y productos del campo">alimetos y productos del campo
  34.                         <td><input type="radio" name="actividad" value="transporte">transporte
  35.                         <td><input type="radio" name="actividad" value="maderas y muebles">madera y muebles
  36.                     </tr>
  37.                     <tr>
  38.                         <td><input type="radio" name="actividad" value="combustible y mineria">combustible y mineria
  39.                         <td><input type="radio" name="actividad" value="comercio">comercio
  40.                         <td><input type="radio" name="actividad" value="vendedor ambulante">vendedor ambulante
  41.                     </tr>
  42.                     <tr>
  43.                         <td><input type="radio" name="actividad" value="confecciones textiles,cuero,bisuteria">confecciones (textiles,cuero,bisuteria)
  44.                         <td><input type="radio" name="actividad" value="restaurantes">restaurantes
  45.                         <td><input type="radio" name="actividad" value="servicio profecionales">servicios profecionales
  46.                     </tr>
  47.                     <tr>
  48.                         <td><input type="radio" name="actividad" value="artesanias">artesanias
  49.                         <td><input type="radio" name="actividad" value="hoteles y turismo">hoteles y turismo
  50.                         <td><input type="radio" name="actividad" value="ceramica y construccion">ceramica y ocnstruccion
  51.                     </tr>
  52.                     <tr>
  53.                         <td><input type="radio" name="actividad" value="otros" checked="checked">otros
  54.                     </tr>
  55.                    
  56.                    
  57.                 </table>
  58.                 <br>
  59.                 <table align="center" width="95%">
  60.                     <tr>
  61.                         <td><b>DESCRIPCION ACTIVIDAD:</b> <input type="text" name="descripcion" size="105%">
  62.                     </tr>
  63.                 </table>
  64.                 <br>
  65.                 <table align="center" width="95%">
  66.                     <tr>
  67.                         <td><b>MATRICULA:</b> <input type="radio" name="matricula" value="si">Si <input type="radio" name="matricula" value="no" checked="checked">No
  68.                         <td><b>INDUSTRIA Y COMERCIO:</b> <input type="radio" name="indycio" value="si">Si <input type="radio" name="indycio" value="no" checked="checked">No
  69.                         <td><b>RIESGO ALTO:</b> <input type="radio" name="riesgo" value="si">Si <input type="radio" name="riesgo" value="no" checked="checked">No  
  70.                     </tr>
  71.                 </table>
  72.                 <br>
  73.                 <table align="center" width="95%">
  74.                     <tr>
  75.                         <td><b>HORARIO DE ATENCION:<br><br> DIURNO:</b> <input type="text" name="horariod" size="40%"> <b>NOCTURNO:</b> <input type="text" name="horarion" size="40%">
  76.                     </tr>
  77.                 </table>
  78.                 <table align="center" width="95%">
  79.                     <tr>
  80.                         <td><b>TIEMPO DE FUNCIONAMIENTO:</b> <input type="text" name="tiempo" size="100%">
  81.                     </tr>
  82.                 </table>
  83.                 <table align="center" width="95%">
  84.                     <tr>
  85.                         <td><b>OBSERVACIONES:</b> <input type="text" name="observaciones" size="112%">
  86.                     </tr>
  87.                 </table>
  88.                 <br> <br>
  89.                 <table align="center" width="95%">
  90.                     <td align="center"><input type="button"  onclick="comprobar_formulario(this.form)" value="Enviar formulario"/>
  91.                 </table>
  92.             </form>




espero que te haya servido de ayuda ...

Etiquetas: campos, formulario, html, obligatorios
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 10:58.