www.webdeveloper.com
Results 1 to 7 of 7

Thread: Form Validation Hopeless

  1. #1
    Join Date
    Jan 2009
    Posts
    9

    Unhappy Form Validation Hopeless

    I appreciate any help!

    Ok, so we have a php article submission script for our community but on the form page I can not achieve form validation for the life of me.

    I have used pretty much any JavaScript method out there, neither work or give any real result of success. I am not skilled enough with PHP to figuere out a PHP method.

    Our form goes as this:

    PHP Code:
    elseif ($action == "add") {
      
    // do_auth(1);  Disabled so the public can submit
      
    echo create_menu();
      echo 
    "<br>
        <form action='?action=process-add' method='post'>
        <table cellspacing='0' cellpadding='0' border='0' align='center'>
        <tr><th>Uploader:</th><td><input type='text' name='name' value='" 
    $session_username "' size='30' maxlength='100'></td></tr>
        <tr><th>Title:</th><td><input type='text' name='title' value='" 
    $title "' size='30' maxlength='150'></td></tr>
        <tr><th>Public:</th><td><input name='public' type='radio' value='yes' checked>Yes <input name='public' type='radio' value='no' disabled>No</td></tr>
        <tr><th valign='top'>Description:</th><td><textarea rows='10' cols='77' name='description'>" 
    $description "</textarea></td></tr>
        <tr><th valign='top'>Document:</th><td><input type='text' name='text'>" 
    $text "</textarea></td></tr>";
      
    $cat_sql "SELECT name FROM sa_category";
      
    db_login();
      
    $cat = @ mysql_query($cat_sql) or die("Getting Categories error: " mysql_error());
      
    $category_r mysql_num_rows($cat);
      
    mysql_close();
      if (
    $category_r == "0") {
        echo 
    "ERROR: No categories in database!";
      }
      else {
        echo 
    "<tr><th>Category:</th><td>
        <select name='category'>
        <option value=''>Select One\n
        <option value=''>------------\n"
    ;
        while (
    $db mysql_fetch_array($cat)) {
          
    $cat_name stripslashes($db['name']);
          echo 
    "<option value='" urlencode($cat_name) . "'>" $cat_name "\n";
        }
        echo 
    "</select>";
      }
      echo 
    "
         </td></tr>
         <tr><th>Convert Newlines(\\n)<br>to HTML Breaks?</th><td><input type='radio' name='nlbr' value='yes' checked>Yes <input type='radio' name='nlbr' value='no'>No</td></tr>
         <tr><td><input type='submit' value='Add'></td><td><input type='reset'></td></tr>
         </table>
         </form>"

    Then when a user clicks "Add" it gives a javascript window saying "Article successfully posted. Thanks!" found on this line right after the above code:

    PHP Code:
    }
    elseif (
    $action == "process-add") {
      
    $nlbr $_POST['nlbr'];
      
    $name mysql_escape_string($_POST['name']);
      
    $title mysql_escape_string($_POST['title']);
      
    $public mysql_escape_string($_POST['public']);
      
    $date mysql_escape_string(date("l F dS, Y h:i A"));
      
    $count 0;
      
    $description $_POST['description'];
      
    $text $_POST['text'];
      
    $category urldecode($_POST['category']);
      
    $category addslashes(mysql_escape_string($category));
      if (
    $nlbr == "yes") {
        
    $text nl2br($text);
    //if it didnt work as expected, use str_replace() instead
        
    $description nl2br($description);
    //if it didnt work as expected, so use str_replace() instead
    //$text = str_replace("\n", "<br>", $text); //if the nl2br dont work comment it and uncomment these
    //$description = str_replace("\n", "<br>", $description); //if the nl2br dont work comment it and uncomment these
      
    }
      
    $text mysql_escape_string($text);
      
    $description mysql_escape_string($description);
      
    $sql "INSERT INTO `sa_page` (`id`, `name`, `title`, `time`, `public`, `count`, `description`, `text`, `category`) VALUES ('', '$name', '$title', '$date', '$public', '$count', '$description', '$text', '$category')";
      
    db_login();
      @ 
    mysql_query($sql) or die("Error inserting! Reason: " mysql_error());
      
    mysql_close();
      
    jsalert("Article successfully posted. Thanks!"); //  Success Javascript Alert   //
      
    jsredirect("?action=view");


    My question is, how do I add a form validation into this to ensure that all fields are filled? I have added every possiblity into the form element (onclick, name, etc etc) linking to both embeded and external JavaScript's with no luck.

    Is this jsalert function that handles the alert spoiling this whole deal? I would really appreciate any help!

    Thank you. This forum looks amazing.. so much information, I'll be reading a lot for sure.
    Last edited by lazzledazzle; 08-07-2009 at 02:24 AM. Reason: Forgot to specify something

  2. #2
    Join Date
    Aug 2009
    Posts
    20
    First of all, would you like to validate on the server side or the client side?
    • Server side validation is more secure and reliable. It doesn't rely on a browser supporting (or allowing) Javascript, and prevents hackers from injecting invalid data.
    • Client side validation is snappier because it happens on the client side!


    Let me know which you prefer; the former requires PHP while the latter needs Javascript.

    Also, if you're using PHP 5, I recommend checking out the following:
    • "Quick print" - instead of echoing a big string, you could just have an HTML section and use <?=$var?> to insert the value of $var into your HTML. It works just like <?php print $var?>, but it's a bit shorter.
    • PDO - PHP Data Objects take care of string escaping in MySQL queries for you. Example:
      PHP Code:
      $sth $dbh->prepare('SELECT name, colour, calories
          FROM fruit
          WHERE calories < ? AND colour = ?'
      );
      $sth->execute(array(150'red'));
      $red $sth->fetchAll(); 
      Notice how the ?'s in the query are replaced with corresponding parameters in the array passed to execute, yielding:
      "SELECT name, colour, calories FROM fruit WHERE calories < '150' AND colour = 'red'".

      It's much easier than making all those variables!

  3. #3
    Join Date
    Jan 2009
    Posts
    9
    Our server is using PHP4. But, curious is there any possible way to add successful form validation with the code provided? This is a big problem because users are submitting blank articles through this and the script doesn't know up from down.

    Any help is appreciated, I'll keep in mind about the Quick print.

  4. #4
    Join Date
    Aug 2009
    Posts
    20

    Lightbulb

    If you're going to validate forms, one of two things should happen when the user clicks "Submit": they have validation errors, or they get a success message. It's helpful when the errors appear next to the affected fields, so you need a way to relate errors to fields. I'll use an array.

    Start by creating an empty $errors array.
    PHP Code:
    $errors = array(); 
    Then, check each field.
    PHP Code:
    if (empty($_POST['field_name'])) {
        
    $errors['field_name'] = "You need to enter a value for this field.";

    If there were no errors, then your $errors array will have no elements.
    PHP Code:
    if ( count($errors) == ) {
        
    // 1. successful!
    } else {
        
    // 2. show the page with errors and the values the user entered.

    For case 2, you'll want to output the values the user entered, as well as the errors. That means, for a text field:

    PHP Code:
    echo '<label for="field_name">Field Name:</label>'// field label
    if ( !empty( $errors['field_name'] ) ) // if this entry exists
        
    echo '<span class="error">' $errors['field_name'] . '</span>';
    echo 
    '<input type="text" name="field_name" value="';
    if ( !empty( 
    $_POST['field_name'] ) )
        echo 
    htmlentities($_POST['field_name']);
    echo 
    '" />'
    Be careful about outputting the variables you initialized with mysql_escape_string() because those will have backslashes around every quote or backslash. It's good for MySQL queries but not for users.
    • If you use the raw POST data and still see backslashes on your quotes, time to turn off PHP magic quotes.
    • You should run user-submitted data through htmlentities() before outputting it. It basically replaces < with &lt; and > with &gt;, among other things. This prevents users from injecting malicious Javascript into submissions.
    • If your articles allow HTML, there may be an XML parser in your validation future. An XML parser will make sure all open tags have a closing tag, etc.
    • Don't use htmlentities() on data that's just going into a database; mysql_escape_string() is fine.


    By the way, it sounds like there are tools out there which will do this for you. Have you ever checked out the Drupal Content Management System? If your needs are fairly simple, you might save some time (otherwise you really won't). The latest version, 6, is compatible with your PHP4 server, and is full of powerful modules that take care of the coding for you.

  5. #5
    Join Date
    Jan 2009
    Posts
    9
    Could you by any chance integrate the validation fix into the code I provided? Thank you.

  6. #6
    Join Date
    Jan 2009
    Posts
    9
    Too late buddy you smell like a fcking butter nipple! ^-.

  7. #7
    Join Date
    Jan 2009
    Posts
    9
    hahahahhaaaaaaaaaaaaaaaaaa

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles