Foros del Web » Programando para Internet » Javascript »

Validar campos checkbox y radio

Estas en el tema de Validar campos checkbox y radio en el foro de Javascript en Foros del Web. Buenas, tengo un problema a la hora de validar los campos checkbox y radio de mi formulario. Tengo un php que hace parte del trabajo ...
  #1 (permalink)  
Antiguo 13/02/2013, 11:23
 
Fecha de Ingreso: enero-2011
Mensajes: 9
Antigüedad: 13 años, 3 meses
Puntos: 0
Validar campos checkbox y radio

Buenas, tengo un problema a la hora de validar los campos checkbox y radio de mi formulario. Tengo un php que hace parte del trabajo y se ayuda de un js.

Tengo validados los campos de texto y los select pero no doy con la formula para validar los checkbox y radio. He probado a hacerlo con una funcion java y funciona, pero en este caso habria 2 codigos para validar, el java y el que hay para validar campos de textos y select. Por lo que cuando le doy enviar, si el resto de campos excepto los checkbox y radio estan bien, se envia el formulario, quedando sin validar los checkbox y radios. No se si suena algo confusa la explicacion :S

Os pego el php:
Código PHP:
Ver original
  1. <?php
  2.  
  3. $nameError = '';
  4. $emailError = '';
  5. $direccionError = '';
  6. $tipopelisError = '';
  7. $sexoError = '';
  8. $commentError = '';
  9.  
  10. if(isset($_POST['submitted'])) {
  11.  
  12.     if(trim($_POST['checking']) !== '') {
  13.         $captchaError = true;
  14.     } else {
  15.    
  16.         //error en el nombre
  17.         if(trim($_POST['contactName']) === '') {
  18.             $nameError = 'Olvidaste escribir tu nombre';
  19.             $hasError = true;
  20.         } else {
  21.             $name = trim($_POST['contactName']);
  22.         }
  23.        
  24.         //error en mail
  25.         if(trim($_POST['email']) === '')  {
  26.             $emailError = 'Olvidaste escribir tu dirección de correo';
  27.             $hasError = true;
  28.         } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
  29.             $emailError = 'Dirección de correo errónea';
  30.             $hasError = true;
  31.         } else {
  32.             $email = trim($_POST['email']);
  33.         }
  34.        
  35.         //error en el direccion
  36.         if(trim($_POST['direccion']) === '') {
  37.             $direccionError = 'Olvidaste escribir tu direccion';
  38.             $hasError = true;
  39.         } else {
  40.             $direccion = trim($_POST['direccion']);
  41.         }
  42.  
  43.         //$tipopelisError = isset($_POST["tipopelis"]);
  44.         if(trim($_POST['tipopelis']) !== '') {
  45.         $tipopelisError = true;
  46.         }
  47.        
  48.         if(trim($_POST['ciudad']) === '') {
  49.             $ciudadError = 'Olvidaste rellenar este campo';
  50.             $hasError = true;
  51.         } else {
  52.             $ciudad = trim($_POST['ciudad']);
  53.         }
  54.            
  55.         //error en comentarios 
  56.         if(trim($_POST['comments']) === '') {
  57.             $commentError = 'Olvidaste escribir un comentario';
  58.             $hasError = true;
  59.         } else {
  60.             if(function_exists('stripslashes')) {
  61.                 $comments = stripslashes(trim($_POST['comments']));
  62.             } else {
  63.                 $comments = trim($_POST['comments']);
  64.             }
  65.         }
  66.        
  67.         $tipopelis = trim($_POST['tipopelis']);
  68.         $sexo = trim($_POST['sexo']);
  69.        
  70.         //Si no hay error, se envia
  71.         if(!isset($hasError)) {
  72.  
  73.             $emailTo = '[email protected]';
  74.             $subject = 'Formulario Hazte Socio Cines Dreams, '.$name;
  75.             $sendCopy = trim($_POST['sendCopy']);
  76.             //$emailreply = '[email protected]';
  77.            
  78.             foreach($_POST['tipopelis'] as $value) {
  79.                 $check_msg .= "Tipo de película: $value\n";
  80.             }
  81.  
  82.             $sexo = $_POST['sexo'];
  83.            
  84.             $body = "Nombre: $name \n\nCorreo electrónico: $email \n\nDirección: $direccion \n\n$check_msg\nSexo: " . $_POST['sexo'] . "\n\nCiudad: $ciudad \n\nMensaje: $comments";
  85.            
  86.             $headers = 'De: prueba <'.$emailTo.'>';// . "\r\n" . 'Responde a: ' . $emailreply;
  87.            
  88.             mail($emailTo, $subject, $body, $headers);
  89.  
  90.             if($sendCopy == true) {
  91.                 $subject = 'Re-envio de formulario ';
  92.                 $headers = 'De: tu nombre <[email protected]>';
  93.                 mail($email, $subject, $option, $body, $headers);
  94.             }
  95.  
  96.             $emailSent = true;
  97.  
  98.         }
  99.     }
  100. } ?>
  101.  
  102. <?php global $theme; get_header(); ?>
  103.  
  104. <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/scripts/contact-form.js"></script>
  105.  
  106.     <div id="main">
  107.  
  108.         <?php $theme->hook('main_before'); ?>
  109.  
  110.         <div id="content">
  111.  
  112.             <?php $theme->hook('content_before'); ?>
  113.  
  114.             <?php if(isset($emailSent) && $emailSent == true) { ?>
  115.  
  116.     <div class="thanks">
  117.         <h1>Gracias, <?=$name;?></h1>
  118.         <p>Tu e-mail ha sido enviado correctamente. Estamos en contacto</p>
  119.     </div>
  120.  
  121. <?php } else { ?>
  122.  
  123.     <?php if (have_posts()) : ?>
  124.    
  125.     <?php while (have_posts()) : the_post(); ?>
  126.         <h1><?php the_title(); ?></h1>
  127.         <?php the_content(); ?>
  128.        
  129.         <?php if(isset($hasError) || isset($captchaError)) { ?>
  130.             <p class="error">Ha habido un error al enviar el formulario<p>
  131.         <?php } ?>
  132.    
  133.         <form action="<?php the_permalink(); ?>" name="contactForm" id="contactForm" method="post" >
  134.    
  135.             <div class="forms">
  136.                 <div id="nombre_label"><label for="contactName">Nombre</label>
  137.                     <input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField" />
  138.                     <?php if($nameError != '') { ?>
  139.                         <span class="error"><?=$nameError;?></span>
  140.                     <?php } ?>
  141.                 </div>
  142.                
  143.                 <div id="email_label"><label for="email">e-mail</label>
  144.                     <input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="requiredField email" />
  145.                     <?php if($emailError != '') { ?>
  146.                         <span class="error"><?=$emailError;?></span>
  147.                     <?php } ?>
  148.                 </div>
  149.                
  150.                 <div id="direccion_label"><label for="direccion">Dirección</label>
  151.                     <input type="text" name="direccion" id="direccion" value="<?php if(isset($_POST['direccion']))  echo $_POST['direccion'];?>" class="requiredField" />
  152.                     <?php if($direccionError != '') { ?>
  153.                         <span class="error"><?=$direccionError;?></span>
  154.                     <?php } ?>
  155.                 </div>
  156.                
  157.                 <div id="pelis_label"><label for="tipopelis" id="tipopelis">Tipo pelis</label>
  158.                     <ul>
  159.                     <li><input type="checkbox" name="tipopelis[]" id="tipopelis" value="accion" />Acción
  160.                     <li><input type="checkbox" name="tipopelis[]" id="tipopelis" value="comedia" />Comedia
  161.                     <li><input type="checkbox" name="tipopelis[]" id="tipopelis" value="romantica" />Romántica
  162.                     <li><input type="checkbox" name="tipopelis[]" id="tipopelis" value="aventuras" />Aventuras
  163.                     </ul>
  164.                 </div>
  165.                
  166.                 <div id="sexo_label"><label for="sexo">Sexo</label>
  167.                 <ul>
  168.                 <li><input type="radio" name="sexo" id="sexo" value="hombre">Hombre
  169.                 <li><input type="radio" name="sexo" id="sexo" value="mujer">Mujer
  170.                 </ul>
  171.                 </div>
  172.                
  173.                 <div><label for="ciudad" id="ciudad">Ciudad</label>
  174.                 <select name="ciudad" value="ciudad">
  175.                 <option value="" selected="selected" >Seleccione una opción</option>
  176.                 <option value="madrid">Madrid</option>
  177.                 <option value="barcelona">Barcelona</option>
  178.                 <option value="valencia'">Valencia</option>
  179.                 </select>
  180.                 </div>
  181.                
  182.                 <div class="textarea"><label for="commentsText">Comentarios</label>
  183.                     <textarea name="comments" id="commentsText" rows="20" cols="30" class="requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
  184.                     <?php if($commentError != '') { ?>
  185.                         <span class="error"><?=$commentError;?></span>
  186.                     <?php } ?>
  187.                 </div>
  188.                
  189.                 <div class="inline"><input type="checkbox" name="sendCopy" id="sendCopy" value="true"<?php if(isset($_POST['sendCopy']) && $_POST['sendCopy'] == true) echo ' checked="checked"'; ?> /><label for="sendCopy">Enviar una copia a mi correo</label></div>
  190.                
  191.                 <div class="screenReader"><label for="checking" class="screenReader">Si quieres enviar este formulario, por favor no rellenes este campo</label><input type="text" name="checking" id="checking" class="screenReader" value="<?php if(isset($_POST['checking']))  echo $_POST['checking'];?>" /></div>
  192.                
  193.                 <div class="buttons"><input type="hidden" name="submitted" id="submitted" value="true" /><button type="submit">Enviar</button></div>
  194.                
  195.             </div>
  196.         </form>
  197.    
  198.         <?php endwhile; ?>
  199.     <?php endif; ?>
  200. <?php } ?>
  201.  
  202.             <?php $theme->hook('content_after'); ?>
  203.  
  204.         </div><!-- #content -->
  205.  
  206.     <?php get_sidebars(); ?>
  207.  
  208.         <?php $theme->hook('main_after'); ?>
  209.  
  210.     </div><!-- #main -->
  211.  
  212. <?php get_footer(); ?>

Y aqui va el js, aunque creo que el trabajo de validacion para los checkbox y radio se tiene que hacer en el php

Código Javascript:
Ver original
  1. $(document).ready(function() {
  2.     $('form#contactForm').submit(function() {
  3.         $('form#contactForm .error').remove();
  4.         var hasError = false;  
  5.         $('.requiredField').each(function() {
  6.             if(jQuery.trim($(this).val()) == '') {
  7.                 var labelText = $(this).prev('label').text();
  8.                 $(this).parent().append('<span class="error">Olvidaste introducir tu '+labelText+'</span>');
  9.                 hasError = true;
  10.             } else if($(this).hasClass('email')) {
  11.                 var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  12.                 if(!emailReg.test(jQuery.trim($(this).val()))) {
  13.                     var labelText = $(this).prev('label').text();
  14.                     $(this).parent().append('<span class="error">'+labelText+' erróneo</span>');
  15.                     hasError = true;
  16.                 }
  17.             }
  18.         });
  19.         if(!hasError) {
  20.             $('form#contactForm .buttons button').fadeOut('normal', function() {
  21.                 $(this).parent().append('<img src="/wp-content/themes/prueba/scripts/loader.gif" alt="Loading" height="11" width="16" />');
  22.             });
  23.  
  24.             var formInput = $(this).serialize();
  25.             $.post($(this).attr('action'),formInput, function(data){
  26.                 $('form#contactForm').slideUp("fast", function() {                 
  27.                     $(this).before('<p class="thanks"><h1><strong>Enhorabuena!</strong></h1>Tu e-mail ha sido enviado correctamente.</p>');
  28.                 });
  29.             });
  30.         }
  31.        
  32.         return false;
  33.        
  34.     });
  35. });

Espero que puedan echarme un cable porque no consigo dar con ello.

Muchas gracias

Etiquetas: checkbox, formulario, radiobutton, validacion
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 00:20.