treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Validating Form with Mandatory Fields

  • I have the contact form from the downloads section of this site on my website. However, I keep getting people clicking send without actually filling out the form. I presume people are just interested to see what happens! Is there any way I can make the fields mandatory so the form cannot be submitted unless they are filled out?

    A template of some sort would be most helpful. My PHP and Javascript skills are very weak!

    Thanks!
  • Just wrote this for a friend, its javascript and validates by testing regular expressions. If you need an in depth explanation just let me know and i can comment the shit out of this. But keep in mind that Javascript can be disabled and should have a fallback, server side (php, asp.net, etc).


    <!DOCTYPE html>
    <html>
    <head>
    <title>|| I || LOVE || YOU ||</title>
    <style type="text/css">
    * {
    margin:0;
    padding:0;
    font:12pt 'Georgia', 'HelveticaNeue-Light' , 'Helvetica Neue Light', 'Helvetica Neue', 'Helvetica', 'Arial', 'Lucida Grande';
    }

    #form-wrapper {
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-225px;
    margin-left:-225px;
    height:450px;
    width:450px;
    background:;
    }

    label, input[type=text] {
    margin-bottom:15px;
    }

    label {
    display:block;
    height:50px;
    width:100px;
    float:left;
    }

    input[type=text], select {
    height:50px;
    width:344px;
    float:left;
    color:#0066ff;
    font-size:30pt;
    outline:none;
    -webkit-transition: background 1s ease;
    -moz-transition: background 1s ease;
    -o-transition: background 1s ease;
    -ms-transition: background 1s ease;
    transition: background 1s ease;
    }

    input[type=text]:hover, select:hover {
    background:#e8e8e8;
    }

    input[type=text]:focus, select:focus {
    background:#e8e8e8;
    border:2px solid #1d1d1d;
    -webkit-box-shadow:0 0 3px #151515;
    -moz-box-shadow:0 0 3px #151515;
    box-shadow:0 0 3px #151515;
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
    }

    #button {
    position:relative;
    top:15px;
    width:400px;
    margin:0 auto;
    padding:10px;
    }

    </style>
    <script>
    function formValidator()
    {
    // Quick reference yo..
    var firstname = document.getElementById('firstname');
    var addr = document.getElementById('addr');
    var zip = document.getElementById('zip');
    var state = document.getElementById('state');
    var username = document.getElementById('username');
    var email = document.getElementById('email');

    // Sorry, i can't help myself. This just makes each element tabified by order.
    document.getElementById('firstname').tabIndex="7";
    document.getElementById('addr').tabIndex="6";
    document.getElementById('zip').tabIndex="5";
    document.getElementById('state').tabIndex="4";
    document.getElementById('username').tabIndex="3";
    document.getElementById('email').tabIndex="2";
    document.getElementById('button').tabIndex="1";

    // Check each input in the order that it appears in the form!
    if (isAlphabet(firstname, "Please enter only letters for your name"))
    {
    if (isAlphanumeric(addr, "Numbers and Letters Only for Address"))
    {
    if (isNumeric(zip, "Please enter a valid zip code"))
    {
    if (madeSelection(state, "Please Choose a State"))
    {
    if (lengthRestriction(username, 6, 8))
    {
    if (emailValidator(email, "Please enter a valid email address"))
    {
    return true;
    }
    }
    }
    }
    }
    }


    return false;

    }

    function notEmpty(elem, helperMsg)
    {
    if (elem.value.length == 0)
    {
    alert(helperMsg);
    elem.focus(); // set the focus to this input
    return false;
    }
    return true;
    }

    function isNumeric(elem, helperMsg)
    {
    var numericExpression = /^[0-9]+$/;
    if (elem.value.match(numericExpression))
    {
    return true;
    }
    else
    {
    alert(helperMsg);
    elem.focus();
    return false;
    }
    }

    function isAlphabet(elem, helperMsg)
    {
    var alphaExp = /^[a-zA-Z]+$/;
    if (elem.value.match(alphaExp))
    {
    return true;
    }
    else
    {
    alert(helperMsg);
    elem.focus();
    return false;
    }
    }

    function isAlphanumeric(elem, helperMsg)
    {
    var alphaExp = /^[0-9a-zA-Z \-'_]+$/;
    if (elem.value.match(alphaExp))
    {
    return true;
    }
    else
    {
    alert(helperMsg);
    elem.focus();
    return false;
    }
    }

    function lengthRestriction(elem, min, max)
    {
    var uInput = elem.value;
    if (uInput.length >= min && uInput.length <= max)
    {
    return true;
    }
    else
    {
    alert("Please enter between " + min + " and " + max + " characters");
    elem.focus();
    return false;
    }
    }

    function madeSelection(elem, helperMsg)
    {
    if (elem.value == "Please Choose")
    {
    alert(helperMsg);
    elem.focus();
    return false;
    }
    else
    {
    return true;
    }
    }

    function emailValidator(elem, helperMsg)
    {
    var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
    if (elem.value.match(emailExp))
    {
    return true;
    }
    else
    {
    alert(helperMsg);
    elem.focus();
    return false;
    }
    }
    </script>
    </head>

    <body>

    <div id="form-wrapper">

    <form onsubmit='return formValidator()'>

    <label for="firstname">First Name:</label>
    <input type='text' id='firstname'>

    <label for="addr">Address:</label>
    <input type='text' id='addr'>

    <label for="zip">Zip Code:</label>
    <input type='text' id='zip'>

    <label for="username">Username:</label>
    <input type='text' id='username'>

    <label for="email">Email:</label>
    <input type='text' id='email'>

    <label for="state">State:</label>
    <select id='state'>
    <option>Please Choose</option>
    <option>AL</option>
    <option>CA</option>
    <option>TX</option>
    <option>WI</option>
    </select>

    <input type='submit' id='button' value='Validate'>

    </form>

    </div><!--end #form-wrapper-->

    </body>
    </html>
  • For PHP, this is a test form i played around with a while back == contact.php

    The workin example is on one of my garbage free sits...
    http://jmotyljr.atwebpages.com/

    This one, however is not my code. This is a dreamweaver tutorial site or something. Information link:

    - Contact Form Designed by James Brand @ dreamweavertutorial.co.uk -->

    - Covered under creative commons license - http://dreamweavertutorial.co.uk/permissions/contact-form-permissions.htm -->


    <?php

    // Set email variables
    $email_to = 'thisIsYourEmail@Address.com';
    $email_subject = 'Form submission';

    // Set required fields
    $required_fields = array('fullname','email','comment');

    // set error messages
    $error_messages = array(
    'fullname' => 'Please enter a Name to proceed.',
    'email' => 'Please enter a valid Email Address to continue.',
    'comment' => 'Please enter your Message to continue.'
    );

    // Set form status
    $form_complete = FALSE;

    // configure validation array
    $validation = array();

    // check form submittal
    if(!empty($_POST)) {
    // Sanitise POST array
    foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));

    // Loop into required fields and make sure they match our needs
    foreach($required_fields as $field) {
    // the field has been submitted?
    if(!array_key_exists($field, $_POST)) array_push($validation, $field);

    // check there is information in the field?
    if($_POST[$field] == '') array_push($validation, $field);

    // validate the email address supplied
    if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
    }

    // basic validation result
    if(count($validation) == 0) {
    // Prepare our content string
    $email_content = 'New Website Comment: ' . "\n\n";

    // simple email content
    foreach($_POST as $key => $value) {
    if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
    }

    // if validation passed ok then send the email
    mail($email_to, $email_subject, $email_content);

    // Update form switch
    $form_complete = TRUE;
    }
    }

    function validate_email_address($email = FALSE) {
    return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
    }

    function remove_email_injection($field = FALSE) {
    return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
    }

    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title>Contact Form</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <link href="contact/css/contactform.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools-yui-compressed.js"></script>
    <script type="text/javascript" src="contact/validation/validation.js"></script>
    <script type="text/javascript">
    var nameError = '<?php echo $error_messages['fullname']; ?>';
    var emailError = '<?php echo $error_messages['email']; ?>';
    var commentError = '<?php echo $error_messages['comment']; ?>';
    function MM_preloadImages() { //v3.0
    var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
    }
    </script>

    </head>

    <body onload="MM_preloadImages('contact/images/x.png')">

    <div id="formWrap">
    <h2>We Appreciate Your Feedback</h2>

    <div id="form">
    <?php if($form_complete === FALSE): ?>
    <form action="contact.php" method="post" id="comments_form">
    <div class="row">
    <div class="label">Your Name</div><!-- end of .label -->
    <div class="input">
    <input type="text" id="fullname" class="detail" name="fullname" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" /><?php if(in_array('fullname', $validation)): ?><span class="error"><?php echo $error_messages['fullname']; ?></span><?php endif; ?>
    </div><!--end of .input -->
    <div class="context">e.g. John Smith</div><!-- end of .context -->
    </div><!-- end of .row -->

    <div class="row">
    <div class="label">Your email address</div><!-- end of .label -->
    <div class="input">
    <input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
    </div><!--end of .input -->
    <div class="context">We will not use your email address with anyone</div><!-- end of .context -->
    </div><!-- end of .row -->

    <div class="row">
    <div class="label">Your Message</div><!-- end of .label -->
    <div class="input2">
    <textarea id="comment" name="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea><?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
    </div><!--end of .input -->
    </div><!-- end of .row -->

    <div class="submit">
    <input type="submit" id="submit" name="submit" value="Send Message">
    </div><!-- end of .submit -->

    </form>
    <?php else: ?>
    <p style="font-size:35px; font-family:Arial, Helvetica, sans-serif; color:#255e67;margin-left:25px;">Thank you for your Message!</p>
    <script type="text/javascript">
    setTimeout('ourRedirect()',3000) //Sets for 3 seconds MO-FO!
    function ourRedirect()
    {
    location.href='index.html'
    }
    </script>
    <?php endif; ?>

    </div><!-- end of #form -->
    </div><!-- end of #formWrap -->


    </body>
    </html>

  • Thanks alot _John_ That was most helpful of you!
  • Your welcome man, kinda perfect timing actually :) Like i said, if you need anything to be clarified just let me know :)