SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot
    Join Date
    Jun 2006
    Location
    Australia
    Posts
    186
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Questioning JS and PHP form validation

    Et al
    A recent thread I started , http://www.sitepoint.com/forums/showthread.php?t=627442,for some help on PHP form validation has, for me at least, lead to some futher questions about form validation using both JS and PHP.
    Some background -
    I have for a while now been attempting to do a catalogue ordering form for my wife's business. I have the JS validation working ok but the PHP, despite many attempts, has defeated me. The problems seem to revolve around
    1. Getting the PHP validation to even be called consistently
    2. How do we tell the user via PHP that the form has an error and where that error may be?

    But it raised more fundamental questions. In last thread a user asked, quite reasonably I think, why am I bothering with JS validation anyway?
    Many posts, threads on these and other fora note that JS is used for client side validation whilst PHP is used for server side validation. They further note that the PHP is a backup validation in case the user has JS turned off, an error occurs etc:

    Questions without notice: -
    A. Do we need to JS validation anymore? It is time to shelve it and stick to just PHP? What is the consensus of opinion these days?

    B. If the consensus is that JS is still useful then can someone please explain clearly and coherently to me how we can use both JS and PHP validation in the same form(s) or page?

    My form has the line
    HTML Code:
    <form method="post" name="catalogue" onsubmit="return valFrm()" action="cataloguetest-8.php";>
    The JS is called via the onsubmit (which works fine) while the PHP is via the action. Is this correct? Or do I have it totally wrong and what is a better (read works) way?
    ========================
    Carn the Tiges!
    www.petalsandpatches.com

  2. #2
    SitePoint Enthusiast Linkoroo's Avatar
    Join Date
    Jul 2009
    Location
    linkoroo.com
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Linkoroo is all php validation. You have to be prepared if the user has js turned off.

    To know which field was wrong, I store information in 2 $_SESSION arrays.

    1 - For the errors
    2 - For user input because you want to prefill what was good.

    ex:

    $_SESSION['err'] = array()
    if($_POST['name'] == "") $_SESSION['err'][] = "Name can't be left empty";

    $_SESSION['inp'] = array();
    $_SESSION['inp']['name'] = $_POST['name'];

    This isn't exactly how I'm doing it but it should give you a good idea. Now you have to clear these sessions at the bottom of the page you it doesn't interfere with your other pages.

    Hope that helps.

  3. #3
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    It's not a case of people moving from JS validation to PHP validation. Server side validation should ALWAYS be used, but now more and more people are adding JavaScript validation AS WELL as PHP.

    There are many benefits, mainly the added usability and responsiveness.

    For example, say you type in a 4 letter password but you want a minimum of 6 characters - telling them after they submit the form is an annoyance, but telling them as soon as they leave the input field would be much better in terms of usablilty.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  4. #4
    SitePoint Enthusiast Linkoroo's Avatar
    Join Date
    Jul 2009
    Location
    linkoroo.com
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Good point arkinstall. Some things should be left to JS and other to PHP.

  5. #5
    SitePoint Wizard cranial-bore's Avatar
    Join Date
    Jan 2002
    Location
    Australia
    Posts
    2,634
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You are correct that server side validation is the only required one, however there is a lot of value having JS validation too. Probably 90&#37; or more of your users will have JS enabled. They will get much faster responses (no waiting for the page to reload) and therefore have a better user experience.

    The client (JS) and server (PHP) side validation run completely separately from one another. In your example your onsubmit handler would actually cancel the form submission if any errors are found. This means that the server doesn't receive the posted form if there were errors that JS caught. If JS doesn't stop the form submission the data will be posted to your action script and PHP can do it's thing.

    JS validation can also run before the submission. For example JS will often listen to the blur event of particular form fields and validate them individually after the user has moved off them. Onsubmit checking is still useful to check fields that were never focused, and to check relationships between fields (if one depends on the other).

    Using both together is not any harder than using one or the other individually. First get your PHP validation happening. It should provide specific reasons the submission was rejected, and also repopulate the form fields with what the user entered, so they don't have to redo the whole thing. Once you have that working you can your JS validation on top.

    Here is a simplified example of server side validation, where the form is repopulated. If your comfortable with OOP I'd recommend that instead of procedural code like this:
    PHP Code:
    <?php
    //Default form values
    $name '';
    $country 'new zealand';
    $phone '';

    /* Process form submission
    --------------------------- */
    if(isset($_POST['name'])) {
        
    $error_msg = array();
        
        
    //Name
        
    $name trim($_POST['name']);
        if(
    strlen($name) < 6) {
            
    $error_msg[] = 'Full name is required';
        }
        
        
    //Country
        
    $country trim(strtolower($_POST['country']));
        if(!
    in_array($country, array('australia''new zealand''france''turkey'))) {
            
    $error_msg[] = 'Sorry, we only ship to Australia, New Zealand, France and Turkey';
        }
        
        
    //Phone
        
    $phone trim($_POST['phone']);
        if(!
    preg_match('/^[0-9]{10,15}$/'$phone)) {
            
    $error_msg[] = 'Phone number must be numbers only, between 10 and 15 digits';
        }
        
        
    //No errors - process the form
        
    if(!$error_msg)) {
            
    //do stuff here
            //display success messsage
        
    }
    }


    /* Display errors, capture input for form
    ----------------------------------------- */
    if(isset($error_msg[0])) {
        
        
    //Display specific errors to user
        
    $errors "<p>The following errors occurred:</p>";
        
    $errors .= "<ul>";
        foreach(
    $error_msg as $e) {
            
    $errors .= "<li>$e</li>";
        }
        echo 
    $errors "</ul>";
        
        
    //Escape user input to be put back 
        //into the HTML to repopulate form
        
    $name htmlspecialchars($nameENT_QUOTES);
        
    $country htmlspecialchars($countryENT_QUOTES);
        
    $phone htmlspecialchars($phoneENT_QUOTES);
    }

    ?>
    <form method="post" action="this-script.php">
    Name <input type="text" name="name" value="<?php echo $name;?>">
    Country <input type="text" name="name" value="<?php echo $country;?>">
    Phone <input type="text" name="name" value="<?php echo $phone;?>" maxlength="15">

    <input type="submit" name="orderBtn" value="Order Now">
    </form>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •