Validar campos checkbox y radio en formulario

Iniciado por rochudo, 14 Febrero 2013, 12:03 PM

0 Miembros y 1 Visitante están viendo este tema.

rochudo

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) [Seleccionar]

<?php 
 
$nameError 
'';
$emailError '';
$direccionError '';
$tipopelisError '';
$sexoError '';
$commentError '';
 
if(isset(
$_POST['submitted'])) {
 
    if(
trim($_POST['checking']) !== '') {
        
$captchaError true;
    } else {
    
        
//error en el nombre
        
if(trim($_POST['contactName']) === '') {
            
$nameError 'Olvidaste escribir tu nombre';
            
$hasError true;
        } else {
            
$name trim($_POST['contactName']);
        }
        
        
//error en mail
        
if(trim($_POST['email']) === '')  {
            
$emailError 'Olvidaste escribir tu dirección de correo';
            
$hasError true;
        } else if (!
eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$"trim($_POST['email']))) {
            
$emailError 'Dirección de correo errónea';
            
$hasError true;
        } else {
            
$email trim($_POST['email']);
        }
        
        
//error en el direccion
        
if(trim($_POST['direccion']) === '') {
            
$direccionError 'Olvidaste escribir tu direccion';
            
$hasError true;
        } else {
            
$direccion trim($_POST['direccion']);
        }
 
        
//$tipopelisError = isset($_POST["tipopelis"]);
        
if(trim($_POST['tipopelis']) !== '') {
        
$tipopelisError true;
        }
        
        if(
trim($_POST['ciudad']) === '') {
            
$ciudadError 'Olvidaste rellenar este campo';
            
$hasError true;
        } else {
            
$ciudad trim($_POST['ciudad']);
        }
            
        
//error en comentarios  
        
if(trim($_POST['comments']) === '') {
            
$commentError 'Olvidaste escribir un comentario';
            
$hasError true;
        } else {
            if(
function_exists('stripslashes')) {
                
$comments stripslashes(trim($_POST['comments']));
            } else {
                
$comments trim($_POST['comments']);
            }
        }
        
        
$tipopelis trim($_POST['tipopelis']);
        
$sexo trim($_POST['sexo']);
        
        
//Si no hay error, se envia
        
if(!isset($hasError)) {
 
            
$emailTo 'rocha.snake@gmail.com';
            
$subject 'Formulario Hazte Socio Cines Dreams, '.$name;
            
$sendCopy trim($_POST['sendCopy']);
            
//$emailreply = 'rodrigo.alba.gomez@gmail.com';
            
            
foreach($_POST['tipopelis'] as $value) {
                
$check_msg .= "Tipo de película: $value\n";
            }
 
            
$sexo $_POST['sexo'];
            
            
$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";
            
            
$headers 'De: prueba <'.$emailTo.'>';// . "\r\n" . 'Responde a: ' . $emailreply;
            
            
mail($emailTo$subject$body$headers);
 
            if(
$sendCopy == true) {
                
$subject 'Re-envio de formulario ';
                
$headers 'De: tu nombre <prueba@gmail.com>';
                
mail($email$subject$option$body$headers);
            }
 
            
$emailSent true;
 
        }
    }
?>


<?php global $themeget_header(); ?>

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/scripts/contact-form.js"></script>

    <div id="main">

        <?php $theme->hook('main_before'); ?>

        <div id="content">

            <?php $theme->hook('content_before'); ?>

            <?php if(isset($emailSent) && $emailSent == true) { ?>

    <div class="thanks">
        <h1>Gracias, <?=$name;?></h1>
        <p>Tu e-mail ha sido enviado correctamente. Estamos en contacto</p>
    </div>

<?php } else { ?>

    <?php if (have_posts()) : ?>
   
    <?php while (have_posts()) : the_post(); ?>
        <h1><?php the_title(); ?></h1>
        <?php the_content(); ?>
       
        <?php if(isset($hasError) || isset($captchaError)) { ?>
            <p class="error">Ha habido un error al enviar el formulario<p>
        <?php ?>
   
        <form action="<?php the_permalink(); ?>" name="contactForm" id="contactForm" method="post" >
   
            <div class="forms">
                <div id="nombre_label"><label for="contactName">Nombre</label>
                    <input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField" />
                    <?php if($nameError != '') { ?>
                        <span class="error"><?=$nameError;?></span>
                    <?php ?>
                </div>
               
                <div id="email_label"><label for="email">e-mail</label>
                    <input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="requiredField email" />
                    <?php if($emailError != '') { ?>
                        <span class="error"><?=$emailError;?></span>
                    <?php ?>
                </div>
               
                <div id="direccion_label"><label for="direccion">Dirección</label>
                    <input type="text" name="direccion" id="direccion" value="<?php if(isset($_POST['direccion']))  echo $_POST['direccion'];?>" class="requiredField" />
                    <?php if($direccionError != '') { ?>
                        <span class="error"><?=$direccionError;?></span>
                    <?php ?>
                </div>
               
                <div id="pelis_label"><label for="tipopelis" id="tipopelis">Tipo pelis</label>
                    <ul>
                    <li><input type="checkbox" name="tipopelis[]" id="tipopelis" value="accion" />Acción
                    <li><input type="checkbox" name="tipopelis[]" id="tipopelis" value="comedia" />Comedia
                    <li><input type="checkbox" name="tipopelis[]" id="tipopelis" value="romantica" />Romántica
                    <li><input type="checkbox" name="tipopelis[]" id="tipopelis" value="aventuras" />Aventuras
                    </ul>
                </div>
               
                <div id="sexo_label"><label for="sexo">Sexo</label>
                <ul>
                <li><input type="radio" name="sexo" id="sexo" value="hombre">Hombre
                <li><input type="radio" name="sexo" id="sexo" value="mujer">Mujer
                </ul>
                </div>
               
                <div><label for="ciudad" id="ciudad">Ciudad</label>
                <select name="ciudad" value="ciudad">
                <option value="" selected="selected" >Seleccione una opción</option>
                <option value="madrid">Madrid</option>
                <option value="barcelona">Barcelona</option>
                <option value="valencia'">Valencia</option>
                </select>
                </div>
               
                <div class="textarea"><label for="commentsText">Comentarios</label>
                    <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>
                    <?php if($commentError != '') { ?>
                        <span class="error"><?=$commentError;?></span>
                    <?php ?>
                </div>
               
                <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>
               
                <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>
               
                <div class="buttons"><input type="hidden" name="submitted" id="submitted" value="true" /><button type="submit">Enviar</button></div>
               
            </div>
        </form>
   
        <?php endwhile; ?>
    <?php endif; ?>
<?php ?>

            <?php $theme->hook('content_after'); ?>

        </div><!-- #content -->

    <?php get_sidebars(); ?>

        <?php $theme->hook('main_after'); ?>

    </div><!-- #main -->

<?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) [Seleccionar]

$(document).ready(function() {
    $('form#contactForm').submit(function() {
        $('form#contactForm .error').remove();
        var hasError = false;   
        $('.requiredField').each(function() {
            if(jQuery.trim($(this).val()) == '') {
                var labelText = $(this).prev('label').text();
                $(this).parent().append('<span class="error">Olvidaste introducir tu '+labelText+'</span>');
                hasError = true;
            } else if($(this).hasClass('email')) {
                var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                if(!emailReg.test(jQuery.trim($(this).val()))) {
                    var labelText = $(this).prev('label').text();
                    $(this).parent().append('<span class="error">'+labelText+' erróneo</span>');
                    hasError = true;
                }
            }
        });
        if(!hasError) {
            $('form#contactForm .buttons button').fadeOut('normal', function() {
                $(this).parent().append('<img src="/wp-content/themes/prueba/scripts/loader.gif" alt="Loading" height="11" width="16" />');
            });

            var formInput = $(this).serialize();
            $.post($(this).attr('action'),formInput, function(data){
                $('form#contactForm').slideUp("fast", function() {                 
                    $(this).before('<p class="thanks"><h1><strong>Enhorabuena!</strong></h1>Tu e-mail ha sido enviado correctamente.</p>');
                });
            });
        }
       
        return false;
       
    });
});


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

Muchas gracias