elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Desarrollo Web
| | |-+  PHP (Moderador: #!drvy)
| | | |-+  Validar campos checkbox y radio en formulario
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Validar campos checkbox y radio en formulario  (Leído 3,149 veces)
rochudo

Desconectado Desconectado

Mensajes: 1


Ver Perfil
Validar campos checkbox y radio en formulario
« en: 14 Febrero 2013, 12:03 pm »

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
  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 = 'rocha.snake@gmail.com';
  74.            $subject = 'Formulario Hazte Socio Cines Dreams, '.$name;
  75.            $sendCopy = trim($_POST['sendCopy']);
  76.            //$emailreply = 'rodrigo.alba.gomez@gmail.com';
  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 <prueba@gmail.com>';
  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(); ?>
  213.  
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
  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. });
  36.  

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

Muchas gracias


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Como validar estos campos
Programación Visual Basic
fedefrankk 7 4,458 Último mensaje 13 Septiembre 2008, 05:11 am
por fedefrankk
como validar campos en sql
.NET (C#, VB.NET, ASP)
Elmonky 1 3,048 Último mensaje 13 Febrero 2012, 23:15 pm
por Elmonky
Validar campos en un arreglo
PHP
Zitros 3 4,082 Último mensaje 8 Marzo 2014, 18:18 pm
por Zitros
Validar mas de un checkbox seleccionado
PHP
danflizz 2 2,841 Último mensaje 17 Mayo 2015, 03:00 am
por danflizz
Validar campos iguales con bootstrap
Desarrollo Web
1mpuls0 2 3,491 Último mensaje 11 Junio 2015, 19:59 pm
por 1mpuls0
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines