简体   繁体   中英

Complex form POST and validation

I asked this question on a previous occasion but obviously no one understood, if only they took the time to look at the link i posted. I am still struggling to get this right and I really need help here.

I have a form to register for a "event"; it requires the name, email and contact number of the person in the first section. Then there are two check boxes for either male or female. If checked male the next section appears for the men's event where they have to select the venue, the time they would like to join and the amount of sessions. Same for when selecting female.

Some of the fields under men do not have a selection but a set value - for instance there is only on venue so I would set the text to display the venue name.

I'll post a link to the form. I get all the display functionality to work but the form posting with AJAX doesn't work.

The problem is that although the "female" section is hidden from display it is still there in code and jQuery wants to validate that section as well. When it comes to posting the form the venue id, time id, and sessions id are the same for men and woman to post the form. I did it like this because is not supposed to show the female section at all in code if "men" are selected.

I think I am doing it all wrong. Should I add each section with jQuery on specific selection of male or female?

Here's what I have at present: http://jsfiddle.net/8U6e2/23/

<h3>Register</h3>

<div class="new_message">
<form action="" method="POST" id="register">
    <fieldset id="personal-info">
        <ul>
            <li class="clearfix">
                <label for="regFirstname">Firstname:</label>
                <input type="text" rel="req" name="regFirstname" id="regFirstname" placeholder="First Name" />  
                <span class="error_message error_regFirstname">*required</span>

            </li>
            <li class="clearfix">
                <label for="regLastname">Lastname:</label>
                <input type="text" rel="req" name="regLastname" id="regLastname" placeholder="Last Name" /> 
                <span class="error_message error_regLastname">*required</span>

            </li>
            <li class="clearfix">
                <label for="regEmail">Email:</label>
                <input type="email" rel="req" name="regEmail" id="regEmail" placeholder="Email" />  
                <span class="error_message error_regEmail">*required</span>

            </li>
            <li class="clearfix">
                <label for="regContact">Contact Number</label>
                <input type="text" name="regContact" id="regContact" placeholder="Contact Number" />    
                <span class="error_message error_regContact">*required</span>

            </li>
            <li class="clearfix radio-select">
                <label for="sex">Male</label>
                <input type="radio" name="regSex" id="regSex" class="men" />
                <label for="sex">Female</label>
                <input type="radio" name="regSex" id="regSex" class="women" />  
                <span class="error_message error_regEmail">*required</span>
            </li>
        </ul>
    </fieldset>
    <fieldset id="women" class="women">
        <ul>
            <li class="clearfix">
                <label for="regVenue">Venue:</label>
                <select name="regVenue" id="regVenue">
                    <option value="">Select a venue</option>
                    <option value="moreleta">this venue1 - women</option>
                    <option value="faerie-glen">this venue2 - women</option>
                </select>   
                <span class="error_message error_regVenue">*required</span>
            </li>
            <li class="clearfix" id="select-time1" value="moreleta">
                <label for="regTime">Time:</label>
                <select name="regTime" id="regTime">
                    <option value="">Select a time slot</option>
                    <option value="8h00">this time1 - venue1</option>
                    <option value="17h15">that time2 - venue1</option>
                </select>   
                <span class="error_message error_regTime">*required</span>
            </li>
            <li class="clearfix" id="select-time2" value="faerie-glen">
                <input type="text" value="5h30 - 6h30 (mornings)" class="hide" />   
                <span class="label">Time:</span> this time - venue2</li>
            <li class="clearfix">
                <label for="timesWeek">Times a week:</label>
                <select name="timesWeek" id="regTimesWeek">
                     <option value="">select frequency...</option>
                    <option value="moreleta">twice a week</option>
                    <option value="faerie-glen">three times a week</option>
                </select>   
                <span class="error_message error_regTimesweek">*required</span>
            </li>
        </ul>
    </fieldset>
    <fieldset id="men" class="men">
        <ul>
            <li class="clearfix"><span class="label">Venue:</span> 
                this venue - men
                <input class="hide" type="text" value="this venue" id="regVenue" name="regVenue"/>
            </li>
            <li class="clearfix"><span class="label">Time:</span> 
                This time - men
                <input class="hide" type="text" value="this venue" id="regTime" name="regTime"/>
            </li>
            <li class="clearfix">
                <label for="timesWeek">Times a week:</label>
                <select name="timesWeek" id="timesWeek">
                    <option value="">select frequency...</option>
                    <option value="twice a week">twice a week</option>
                    <option value="three times a week">three times a week</option>
                </select>
                <span class="error_message error_regTimesweek">*required</span>
            </li>
        </ul>
    </fieldset>
    <input class="buttonLink" type="submit" value="Register" id="regSubmit" />
</form>
</div>

h3{
   font-weight:bold;
   font-size:18px;
   margin-bottom:30px;
}
ul li {
   position:relative;
   margin-bottom:10px;
}

fieldset#women{ display: none;}

fieldset#men{display: none;}

li#select-time1, li#select-time2{
    display: none;
}
label, .label{width:130px;display:inline-block;}
li.radio-select{padding-left: 108px; position: relative;}
li.radio-select label{float: left; width: auto !important; margin-left: 28px;}
li.radio-select input{ float: left; margin-left: 20px;}
span.error_message{background: #e39595;color: white;padding: 3px 12px;border-radius: 5px;position: absolute;top: 0;display: none;z-index: 100;}
.hide{display:none}


// on form selection display appropriate fields 

var $men = $("fieldset.men"),
    $women = $("fieldset.women");

$(':radio.men').on('click', function () {
    if ($women.css('display', 'block' === true)) {
        $women.fadeOut(300, function () {
            $men.fadeIn('slow');
        });
    } else {
        $men.fadeIn('slow');
    }
});

$(':radio.women').on('click', function () {
    if ($men.css('display', 'block' === true)) {
        $men.fadeOut(300, function () {
            $women.fadeIn('slow');
        });
    } else {
        $women.fadeIn('slow');
    }
});

// Change display of times depending on selection made on venues

$('#regVenue').change(function () {
    var selectVal = $('#regVenue option:selected').val(),
        venue1 = $('li#select-time1'),
        venue2 = $('li#select-time2');
    if (selectVal === "moreleta") {
        venue2.fadeOut(300, function () {
            venue1.fadeIn(300);
        });
    }
    if (selectVal === "faerie-glen") {
        venue1.fadeOut(300, function () {
            venue2.fadeIn(300);
        });
    }
});

// form validation and send request

$('#regSubmit').on('click', function () {
    $('.error_message').hide();

    var regFirstname = $('input#regFirstname').val();
    if (regFirstname === "") {
        $("span.error_regFirstname").show();
        $("input#regFirstname").focus();
        return false;
    }
    var regLastname = $('input#regLastname').val();
    if (regLastname === "") {
        $("span.error_regLastname").show();
        $("input#regLastname").focus();
        return false;
    }
    var regEmail = $('input#regEmail').val();
    if (regEmail === "") {
        $("span.error_regEmail").show();
        $("input#regEmail").focus();
        return false;
    }

    var regContact = $('input#regContact').val();
    if (regContact === "") {
        $("span.error_regContact").show();
        $("input#regEmail").focus();
        return false;
    }

    var regSex = $('input#regSex').val();

    var regVenue = $('select#regVenue').val();
    if (regVenue === "") {
        $("span.error_regVenue").show();
        $("select#regVenue").focus();
        return false;
    }
    var regTime = $('select#regTime').val();
    if (regTime === "") {
        $("span.error_regTime").show();
        $("select#regTime").focus();
        return false;
    }

    var regTimesweek = $('select#regTimesweek').val();
    if (regTimesweek === "") {
        $("span.error_regTimesweek").show();
        $("select#regTimesweek").focus();
        return false;
    }


    var info = 'regFirstname=' + regFirstname + '&regLastname=' + regLastname + '&regEmail=' + regEmail + '&regContact=' + regContact + '&sex=' + regSex + '&regVenue=' + regVenue + '&regTime=' + regTime + '&regTimesweek=' + regTimesweek;

    $.ajax({

        type: "POST",
        url: "register_form.php",
        data: info,
        success: function () {
            $('#register_form').html("<div id='new_message'></div>");
            $('#new_message').html("<h3>Thank you for registering to join GO-Active Boot Camp!</h3>").append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function () {
                $('#new_message');
            });
        }
    });
    return false;

});

the php form

<?php

/* Set e-mail recipient */
$myemail  = "me@email.com";
$subject = "Go-Active - Contact Form";

$headers =  'From: me@email.com' . "\r\n" .
        'Reply-To: me@email.com';

$regFirstname = check_input($_POST['regFirstname'], "Please Name");
$regLastname  = check_input($_POST['regLastname'], "Please Name");
$regEmail     = check_input($_POST['regEmail'],"Please enter valid Email Address");
$regContact   = check_input($_POST['regContact'],"Please enter valid Contact Number");
$regSex       = check_input($_POST['regSex'],"Please select you sex");
$regVenue     = check_input($_POST['regVenue'],"Please select a Venue");
$regTime      = check_input($_POST['regTime'],"Please select you Timeslot");
$regTimesweek = check_input($_POST['regTimesweek'],"Please select how many times a week");

$myError = 0;

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $regEmail))
{
   $myError=("E-mail address not valid");
}

/* Let's prepare the message for the e-mail */

$message = "Hello!

Your contact form has been submitted by:

Name:". $regFirstname . " " . $regLastname ."\r\n" .
"E-mail:".$regEmail."\r\n" .
"Subject:".$message_subject."\r\n" . "\r\n" .
"Message:" . "\r\n" . "\r\n" .$content. "\r\n" . "\r\n" .

"End of message";

/* Send the message using mail() function */
@mail($myemail, $subject, $message, $headers);

echo $myError;

function check_input($data,  $problem='')
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($problem && strlen($data) == 0)
       {
           $myError = ($problem);
       }

    return $data;
    }

?>

When your JavaScript checks the form field if it is valid, make it check what gender is selected. If male, validate it, if female, do not (but validate the other field using the same logic).

Like:

if (gender.val() == 'male') { 
    if (myfield.val() == 'what it should be') {
        //Valid
    } else {
        //Invalid
    }
}

You could take it a step further (and make it easier for yourself) by giving each field a special attribute telling your script to validate it.

<input type="text" name="myfield" class="validate email" />

In your jQuery:

$('INPUT.validate').each(function() { ... perform validation ... })

I personally like to use HTML5 data attributes that is compatible with every browser. Eg:

<input type="text" name="myfield" data-validate="email" />

Have fun! (validation is a bitch)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM