Results 1 to 7 of 7

Thread: Form Validation Hopeless

  1. #1
    Join Date
    Jan 2009

    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();
        <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";
    $cat = @ mysql_query($cat_sql) or die("Getting Categories error: " mysql_error());
    $category_r mysql_num_rows($cat);
      if (
    $category_r == "0") {
    "ERROR: No categories in database!";
      else {
        <select name='category'>
        <option value=''>Select One\n
        <option value=''>------------\n"
        while (
    $db mysql_fetch_array($cat)) {
    $cat_name stripslashes($db['name']);
    "<option value='" urlencode($cat_name) . "'>" $cat_name "\n";
         <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>

    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')";
    mysql_query($sql) or die("Error inserting! Reason: " mysql_error());
    jsalert("Article successfully posted. Thanks!"); //  Success Javascript Alert   //

    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
    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 = ?'
      $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
    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


    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>';
    '<input type="text" name="field_name" value="';
    if ( !empty( 
    $_POST['field_name'] ) )
    '" />'
    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
    Could you by any chance integrate the validation fix into the code I provided? Thank you.

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

  7. #7
    Join Date
    Jan 2009

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



X vBulletin 4.2.2 Debug Information

  • Page Generation 0.11590 seconds
  • Memory Usage 2,945KB
  • Queries Executed 15 (?)
More Information
Template Usage (33):
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (7)bbcode_php
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (7)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (7)postbit
  • (7)postbit_onlinestatus
  • (7)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (73):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates