/    Sign up×
Community /Pin to ProfileBookmark

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:

[code=php]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 Onen
<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>”;[/code]

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:

[code=php]}
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”);
}[/code]

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 [B]jsalert[/B] 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.

to post a comment
PHP

6 Comments(s)

Copy linkTweet thisAlerts:
@solowandererY2KAug 07.2009 — First of all, would you like to validate on the server side or the client side?
[LIST]
  • [*]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!

  • [/LIST]


    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:
    [LIST]
  • [*][B]"Quick print"[/B] - 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.

  • [*][B]PDO - PHP Data Objects[/B] take care of string escaping in MySQL queries for you. Example:
    [code=php]
    $sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
    $sth->execute(array(150, 'red'));
    $red = $sth->fetchAll();
    [/code]

    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!

  • [/LIST]
    Copy linkTweet thisAlerts:
    @lazzledazzleauthorAug 07.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. ?
    Copy linkTweet thisAlerts:
    @solowandererY2KAug 07.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.
    [code=php]$errors = array();[/code]

    Then, check each field.
    [code=php]if (empty($_POST['field_name'])) {
    $errors['field_name'] = "You need to enter a value for this field.";
    }[/code]


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


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

    [code=php]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 '" />';
    [/code]


    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.
    [LIST]
  • [*]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.

  • [/LIST]


    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.
    Copy linkTweet thisAlerts:
    @lazzledazzleauthorAug 08.2009 — Could you by any chance integrate the validation fix into the code I provided? Thank you.
    Copy linkTweet thisAlerts:
    @lazzledazzleauthorAug 09.2009 — Too late buddy you smell like a fcking butter nipple! ^-.
    Copy linkTweet thisAlerts:
    @lazzledazzleauthorAug 09.2009 — hahahahhaaaaaaaaaaaaaaaaaa
    ×

    Success!

    Help @lazzledazzle spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.24,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...