Jump to content

php form prevent empty table submit


Faks

Recommended Posts

Well the problem is simple i want to prevent submitting empty textfield or textarea with php code

 

Here is my code ... but it doesn't work as i wish to  :

 

if((empty($text) == "") || strlen($text) < 1){        {        echo "Lūdzu Aizpildat Aili";        }}

 

 

Also somebody advised me to use this code but i found it far more useless then mine ...

 

function check_empty($text){        if(empty($text) || !empty($text) || $text || !$text || $text ^ $text || 1/0)                check_empty(!!!!!$text);                return never_ever;} // check_empty

 

 

Link to comment
Share on other sites

As to your first set of code. empty($text) will return a boolean (true or false), there's no reason to compare that to "":

 

 

if (empty($text) || strlen($text) < 1) {

 

 

In fact, if you're going to check the string length, there's no need to check if the variable is empty at all:

 

 

if (strlen($text) < 1) {

 

 

As to the 2nd chunk of code, that creates an infinite loop. The first part of the if reads:

 

 

if (empty($text) || !empty($text)

 

 

If empty($text) is true, then the or is true, if empty($text) is false, then !empty($text) is true and the or is still true. Thus, the if is ALWAYS true (the statement is a tautology, it cannot be false). The if just runs the same function over again, which will of course result in another true, and will result in the function running again ad infinitum.

Link to comment
Share on other sites

Yeah did ....

if (empty($text) || strlen($text) < 1)
{
    {
     echo "Lūdzu Aizpildat Aili";
    }
}

check the website and try add comment you will see the problem how it's actually is right now ...

Link to comment
Share on other sites

if (isset($_POST['pievienot']))
{
    $text = mysql_real_escape_string($_POST[text]);
    $text = htmlentities($_POST[text]);
    $id   = (int)$_GET['id'];

    $insert = "INSERT INTO comment (comment_name,comment_datetime,comment_text,news_id,comment_ip) VALUES ('".$_SESSION['u_nick']."',NOW(),'".$text."','".$id."','".$ip."')";
    mysql_query($insert) or die(mysql_error());
}


if (empty($text) || strlen($text) < 1)
{
    {
     echo "Lūdzu Aizpildat Aili";
    }
}

echo ("
<h3>Pievienot Komentāru</h3>
<form method='post'>
Komentara Teksts : <br><textarea name='text' cols='40' rows='6'></textarea><br>
<input type='submit'  name='pievienot' value='pievienot' />
</form>");

}
?>

Link to comment
Share on other sites

Your problem is here:

 

$text = mysql_real_escape_string($_POST[text]);

 

Unless the word "text" has been defined as a constant, you're not accessing an index, you need to do:

 

$text = mysql_real_escape_string($_POST['text']);

Not related to my problem skip this and reread whole page see if need watch video to see WHAT'S IS THE DAMM PROBLEM .

Link to comment
Share on other sites

what is the value of $text before it hits the if? echo it and see.

 

then check both of your if conditionals separately: is $text empty? is strlen($text) < 1? basic troubleshooting, here.

did it like said not helping it would be great if there were some examples .....  :rtfm::wtf:

Link to comment
Share on other sites

well i got n1 code but it would be great if somebody will help me sort it out for my use and could distribute it in forum for others .

demo.php

<?php

$errors = array(); // set the errors array to empty, by default
$fields = array(); // stores the field values
$success_message = "";

if (isset($_POST['submit']))
{
  // import the validation library
  require("validation.php");

  $rules = array(); // stores the validation rules

  // standard form fields
  $rules[] = "required,user_name,This field is required.";
  $rules[] = "required,email,Please enter your email address.";
  $rules[] = "valid_email,email,Please enter a valid email address.";

  // date fields
  $rules[] = "valid_date,any_date_month,any_date_day,any_date_year,any_date,Please enter a valid date.";
  $rules[] = "valid_date,later_date_month,later_date_day,later_date_year,later_date,Please enter an date later than today.";

  // Numbers / alphanumeric fields
  $rules[] = "required,any_integer,Please enter an integer.";
  $rules[] = "digits_only,any_integer,This field may only contain digits.";
  $rules[] = "digits_only,number_range,This field may only contain digits.";
  $rules[] = "range=1-100,number_range,Please enter a number between 1 and 100.";
  $rules[] = "range>100,number_range_greater_than,Please enter a number greater than 100.";
  $rules[] = "range>=100,number_range_greater_than_or_equal,Please enter a number greater than or equal to 100.";
  $rules[] = "range<100,number_range_less_than,Please enter a number less than 100.";
  $rules[] = "range<=100,number_range_less_than_or_equal,Please enter a number less than or equal to 100.";
  $rules[] = "letters_only,letter_field,Please only enter letters (a-Z) in this field.";
  $rules[] = "required,alpha_field,Please enter an alphanumeric (0-9 a-Z) string.";
  $rules[] = "is_alpha,alpha_field,Please only enter alphanumeric characters (0-9 a-Z) in this field.";
  $rules[] = "custom_alpha,custom_alpha_field1,LLL-VVV,Please enter a string of form LLL-VVV - where L is an uppercase letter and V is an uppercase vowel.";
  $rules[] = "custom_alpha,custom_alpha_field2,DDxxx,Please enter a string of form DDxxx.";
  $rules[] = "custom_alpha,custom_alpha_field3,EEXX,Please enter a string of form EEXX.";
  $rules[] = "custom_alpha,custom_alpha_field4,VVvvllFF,Please enter a string of form VVvvllFF.";
  $rules[] = "custom_alpha,custom_alpha_field5,#XccccCCCC,Please enter a string of form #XccccCCCC.";
  $rules[] = "reg_exp,reg_exp_field1,^\\s*(red|orange|yellow|green|blue|indigo|violet|pink|white)\\s*$,Please enter your favourite colour in lowercase (e.g. \"red\" or \"blue\")";
  $rules[] = "required,reg_exp_field2,Please enter your favourite colour (e.g. \"red\" or \"blue\")";
  $rules[] = "reg_exp,reg_exp_field2,^\\s*(red|orange|yellow|green|blue|indigo|violet|pink|white)\\s*$,i,Please enter your favourite colour (e.g. \"red\" or \"blue\")";

    
  // Length of field input
  $rules[] = "length=2,char_length,Please enter a value that is exactly two characters long.";
  $rules[] = "length=3-5,char_length_range,Please enter a value that is between 3 and 5 characters in length.";
  $rules[] = "length>5,char_length_greater_than,Please enter a value that is over 5 characters long.";
  $rules[] = "length>=5,char_length_greater_than_or_equal,Please enter a value that is at least 5 characters long.";
  $rules[] = "length<5,char_length_less_than,Please enter a value that is less than 5 characters long.";
  $rules[] = "length<=5,char_length_less_than_or_equal,Please enter a value that is less than or equal to 5 characters.";
  
  // password fields
  $rules[] = "required,password,Please enter a password.";
  $rules[] = "same_as,password,password_2,Please ensure the passwords you enter are the same.";
  
  // conditional (if-else) fields
  $rules[] = "required,gender,Please enter your gender.";
  $rules[] = "if:gender=male,required,male_question,Please enter the name of your favourite Care Bear.";
  $rules[] = "if:gender=female,required,female_question,Please indicate what max weight you can bench.";

  $errors = validateFields($_POST, $rules);

  // if there were errors, re-populate the form fields
  if (!empty($errors))
  {  
    $fields = $_POST;
  }
  
  // no errors! redirect the user to the thankyou page (or whatever)
  else 
  {
    $message = "All fields have been validated successfully!";
    
    // here you would either email the form contents to someone or store it in a database. 
    // To redirect to a "thankyou" page, you'd just do this:
    // header("Location: thanks.php");
  }
}


// don't worry about these. This is just for illustration purposes: it sets a DEFAULT value to some
// fields, which is overwritten when the user fills it in 
if (!isset($fields["custom_alpha_field1"])) $fields["custom_alpha_field1"] = "BCD-AEI";
if (!isset($fields["custom_alpha_field2"])) $fields["custom_alpha_field2"] = "aB012";
if (!isset($fields["custom_alpha_field3"])) $fields["custom_alpha_field3"] = "bB34"; 
if (!isset($fields["custom_alpha_field4"])) $fields["custom_alpha_field4"] = "OUoucgAa"; 
if (!isset($fields["custom_alpha_field5"])) $fields["custom_alpha_field5"] = "#8rtyhWRGS"; 
          
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>PHP Validation Demo</title>

<style type="text/css">
<!--
body,p,table,td,input,select {
  font-family: verdana, tahoma;
    font-size: 8pt;
  line-height: 14pt;
}
.demoTable {
  background-color: #efefef;
  width: 100%;
}
.title { font-family: arial; font-size: 16pt; }
.section { font-size: 11pt; color: #3366cc; }
.error {
  border: 1px solid red;
  background-color: #ffffee;
  color: #660000;
  width: 400px;
  padding: 5px;
}
.notify {
  border: 1px solid #336699;
  background-color: #ffffee;
  color: #336699;
  width: 400px;
  padding: 5px;
}
-->
</style>

</head>
<body>

<table cellspacing="0" width="600" align="center">
<tr>
  <td>
    
    <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
    
    <p class="title">PHP Validation Demo</p>
    
    <p>
      This form contains all the validation options that are offered by the 
      <a href="index.php">PHP Validation library</a>. To see how this works, <a href="php_validation.zip">download    
        the zip file</a>. Since the <b>custom_alpha</b> options are quite advanced
        and unlikely to be used that often (and because it's a pain figuring out a match 
      for all of the cases!) I've filled in matching strings for those fields.
    </p>

    <br />
    
    <?php
    
    // if $errors is not empty, the form must have failed one or more validation 
    // tests. Loop through each and display them on the page for the user
    if (!empty($errors))
    {
      echo "<div class='error' style='width:100%;'>Please fix the following errors:\n<ul>";
      foreach ($errors as $error)
        echo "<li>$error</li>\n";
    
      echo "</ul></div>"; 
    }
    
    if (!empty($message))
    {
      echo "<div class='notify'>$success_message</div>";
    }
    ?>
    
    <p class="section">Standard form fields</p>
    
    <table class="demoTable">
    <tr>
      <td>Required field:</td>
        <td><input type="text" name="user_name" value="<?=$fields['user_name']?>" /></td>
    </tr>
    <tr>
      <td>Email:</td>
        <td><input type="text" name="email" value="<?=$fields['email']?>" /></td>
    </tr>
    </table>
    
    <p class="section">Date fields</p>
    
    <table class="demoTable">
    <tr>
      <td>Any (valid) date</td>
        <td>
        <select name="any_date_month">
            <option value="">mm</option>
            <?php
                for ($i=1; $i<=12; $i++)
          {
            echo "<option value='$i'";
            if ($fields["any_date_month"] == $i)
              echo " selected";
            echo ">$i</option>";
          }
          ?>            
        </select>
        <select name="any_date_day">
            <option value="">dd</option>
            <?php
                for ($i=1; $i<=31; $i++)
          {
            echo "<option value='$i'";
            if ($fields["any_date_day"] == $i)
              echo " selected";
            echo ">$i</option>";
          }
          ?>
        </select>
        <select name="any_date_year">
            <option value="">yyyy</option>
            <?php
                for ($i=2005; $i>=1900; $i--)
          {
            echo "<option value='$i'";
            if ($fields["any_date_year"] == $i)
              echo " selected";
            echo ">$i</option>";
          }
          ?>
        </select>
        </td>
    </tr>
    <tr>
      <td>Any later date:</td>
        <td>
        <select name="later_date_month">
            <option value="">mm</option>
            <?php
                for ($i=1; $i<=12; $i++)
          {
            echo "<option value='$i'";
            if ($fields["later_date_month"] == $i)
              echo " selected";
            echo ">$i</option>";
          }
          ?>            
        </select>
        <select name="later_date_day">
            <option value="">dd</option>
            <?php
                for ($i=1; $i<=31; $i++)
          {
            echo "<option value='$i'";
            if ($fields["later_date_day"] == $i)
              echo " selected";
            echo ">$i</option>";
          }
          ?>            
        </select>
        <select name="later_date_year">
            <option value="">yyyy</option>
            <?php
                for ($i=2010; $i>=1900; $i--)
          {
            echo "<option value='$i'";
            if ($fields["later_date_year"] == $i)
              echo " selected";
            echo ">$i</option>";
          }
          ?>            
        </select>    
        </td>
    </tr>
    </table>
    
    
    <p class="section">Numbers / alphanumeric fields</p>
    
    <table class="demoTable">
    <tr>
      <td width="230">Any integer:</td>
        <td width="350"><input type="text" name="any_integer" value="<?=$fields['any_integer']?>" /></td>
    </tr>
    <tr>
      <td>Enter a number from 1-100:</td>
        <td><input type="text" name="number_range" value="<?=$fields['number_range']?>" /></td>
    </tr>
    <tr>
      <td>Enter a number greater than 100:</td>
        <td><input type="text" name="number_range_greater_than" value="<?=$fields['number_range_greater_than']?>" /></td>
    </tr>
    <tr>
      <td>Enter a number greater than or equal to 100:</td>
        <td><input type="text" name="number_range_greater_than_or_equal" value="<?=$fields['number_range_greater_than_or_equal']?>" /></td>
    </tr>
    <tr>
      <td>Enter a number less than 100:</td>
        <td><input type="text" name="number_range_less_than" value="<?=$fields['number_range_less_than']?>" /></td>
    </tr>
    <tr>
      <td>Enter a number less than or equal to 100:</td>
        <td><input type="text" name="number_range_less_than_or_equal" value="<?=$fields['number_range_less_than_or_equal']?>" /></td>
    </tr>
    <tr>
      <td>Enter any letter:</td>
        <td><input type="text" name="letter_field" value="<?=$fields['letter_field']?>" /> (optional)</td>
    </tr>
    <tr>
      <td>Enter any alphanumeric characters:</td>
        <td><input type="text" name="alpha_field" value="<?=$fields['alpha_field']?>" /> (required)</td>
    </tr>
    <tr>
      <td>Enter strings in the fields according to the following legend:</td>
        <td>
        
          <table cellspacing="0" style="background-color: #ffffcc; border: 1px solid #555555; width:100%">
          <tr>
            <th width="20">L</th>
            <td>An uppercase letter.</td>
            <th width="20">V</th>
            <td>An uppercase vowel.</td>
          </tr>
          <tr>
            <th>l</th>
            <td>A lowercase letter.</td>
            <th>v</th>
            <td>A lowercase vowel.</td>
          </tr>
          <tr>
            <th>D</th>
            <td>A letter (upper or lower)</td>
            <th>F</th>
            <td>A vowel (upper or lower)</td>
          </tr>
          <tr>
            <th>C</th>
            <td>An uppercase Consonant</td>
            <th>x</th>
            <td>Any number, 0-9</td>
          </tr>
          <tr>
            <th>c</th>
            <td>A lowercase consonant</td>
            <th>X</th>
            <td>Any number, 1-9</td>
          </tr>
          <tr>
            <th>E</th>
            <td colspan="3">A consonant (upper or lower)</td>
          </tr>
          </table>
    
        <table cellspacing="0">
        <tr>
          <td><input type="text" name="custom_alpha_field1" value="<?=$fields['custom_alpha_field1']?>" /> LLL-VVV</td>
        </tr>
        <tr>
          <td><input type="text" name="custom_alpha_field2" value="<?=$fields['custom_alpha_field2']?>" /> DDxxx</td>
        </tr>
        <tr>
          <td><input type="text" name="custom_alpha_field3" value="<?=$fields['custom_alpha_field3']?>" /> EEXX</td>
        </tr>
        <tr>
          <td><input type="text" name="custom_alpha_field4" value="<?=$fields['custom_alpha_field4']?>" /> VVvvllFF</td>
        </tr>
        <tr>
          <td><input type="text" name="custom_alpha_field5" value="<?=$fields['custom_alpha_field5']?>" /> #XccccCCCC</td>
        </tr>
        </table>
    
        <br />
    
      </td>
    </tr>
    <tr>
      <td>Enter your favourite colour:</td>
        <td><input type="text" name="reg_exp_field1" value="<?=$fields['reg_exp_field1']?>" /> (lowercase, optional)</td>
    </tr>
    <tr>
      <td>Enter your favourite colour:</td>
        <td><input type="text" name="reg_exp_field2" value="<?=$fields['reg_exp_field2']?>" /> (case-insensitive, required)</td>
    </tr>
    </table>

    <p class="section">Length of field input</p>

    <table class="demoTable">
    <tr>
      <td>Enter 2 characters:</td>
        <td><input type="text" name="char_length" value="<?=$fields['char_length']?>" /></td>
    </tr>
    <tr>
      <td>Enter between 3 and 5 chars:</td>
        <td><input type="text" name="char_length_range" value="<?=$fields['char_length_range']?>" /></td>
    </tr>
    <tr>
      <td>Enter over 5 characters:</td>
        <td><input type="text" name="char_length_greater_than" value="<?=$fields['char_length_greater_than']?>" /></td>
    </tr>
    <tr>
      <td>Enter at least 5 characters:</td>
        <td><input type="text" name="char_length_greater_than_or_equal" value="<?=$fields['char_length_greater_than_or_equal']?>" /></td>
    </tr>
    <tr>
      <td>Enter less than 5 characters:</td>
        <td><input type="text" name="char_length_less_than" value="<?=$fields['char_length_less_than']?>" /></td>
    </tr>
    <tr>
      <td>Enter less than or equal to 5 characters:</td>
        <td><input type="text" name="char_length_less_than_or_equal" value="<?=$fields['char_length_less_than_or_equal']?>" /></td>
    </tr>
    </table>
    
    <p class="section">Password fields</p>
    
    <table class="demoTable">
    <tr>
      <td>Enter a password:</td>
        <td><input type="password" name="password" value="<?=$fields['password']?>" /></td>
    </tr>
    <tr>
      <td>Enter a password (re-enter):</td>
        <td><input type="password" name="password_2" value="<?=$fields['password_2']?>" /></td>
    </tr>
    </table>
    
    <p class="section">Conditional (if-else) fields</p>
    
    <table class="demoTable">
    <tr>
      <td>Your gender:</td>
        <td>
          <input type="radio" name="gender" value="male" <?php if ($fields['gender'] == 'male') echo 'checked'; ?> />Male
            <input type="radio" name="gender" value="female" <?php if ($fields['gender'] == 'female') echo 'checked'; ?> />Female
        </td>
    </tr>
    <tr>
      <td>Who's your favourite Care Bear? (Men):</td>
        <td><input type="text" name="male_question" value="<?=$fields['male_question']?>" /></td>
    </tr>
    <tr>
      <td>How much can you bench (Women):</td>
        <td><input type="text" name="female_question" value="<?=$fields['female_question']?>" /></td>
    </tr>
    </table>
    
    <p><input type="submit" name="submit" value="SUBMIT" /></p>
    
    </form>

    <br />
    
  </td>
</tr>
</table>
        
</body>
</html>

validation.php

<?php

/*--------------------------------------------------------------------------------------------*\

  validation.php
  --------------

  v2.3.3, Apr 2010

  This script provides generic validation for any web form. For a discussion and example usage 
  of this script, go to http://www.benjaminkeen.com/software/php_validation

  This script is written by Ben Keen with additional code contributed by Mihai Ionescu and 
  Nathan Howard. It is free to distribute, to re-write - to do what ever you want with it.

  Before using it, please read the following disclaimer. 

  THIS SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS WITHOUT WARRANTY OF ANY KIND. BENJAMINKEEN.COM 
  SPECIFICALLY DISCLAIMS ANY OTHER WARRANTY, EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF 
  MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL BENJAMINKEEN.COM BE 
  LIABLE FOR ANY CONSEQUENTIAL, INDIRECT, SPECIAL OR INCIDENTAL DAMAGES, EVEN IF BENJAMINKEEN.COM 
  HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH POTENTIAL LOSS OR DAMAGE. USER AGREES TO HOLD 
  BENJAMINKEEN.COM HARMLESS FROM AND AGAINST ANY AND ALL CLAIMS, LOSSES, LIABILITIES AND EXPENSES.

\*--------------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------------*\
  Function: validateFields()
  Purpose:  generic form field validation.
  Parameters: field - the POST / GET fields from a form which need to be validated.
              rules - an array of the validation rules. Each rule is a string of the form:

   "[if:FIELDNAME=VALUE,]REQUIREMENT,fieldname[,fieldname2 [,fieldname3, date_flag]],error message"
  
              if:FIELDNAME=VALUE,   This allows us to only validate a field 
                          only if a fieldname FIELDNAME has a value VALUE. This 
                          option allows for nesting; i.e. you can have multiple 
                          if clauses, separated by a comma. They will be examined
                          in the order in which they appear in the line.

              Valid REQUIREMENT strings are: 
                "required"     - field must be filled in
                "digits_only"  - field must contain digits only
                "is_alpha"     - field must only contain alphanumeric characters (0-9, a-Z)
                "custom_alpha" - field must be of the custom format specified.
                      fieldname:  the name of the field
                      fieldname2: a character or sequence of special characters. These characters are:
                          L   An uppercase Letter.          V   An uppercase Vowel.
                          l   A lowercase letter.           v   A lowercase vowel.
                          D   A letter (upper or lower).    F   A vowel (upper or lower).
                          C   An uppercase Consonant.       x   Any number, 0-9.
                          c   A lowercase consonant.        X   Any number, 1-9.
                          E   A consonant (upper or lower).
                "reg_exp"      - field must match the supplied regular expression.  
                      fieldname:  the name of the field
                      fieldname2: the regular expression
                      fieldname3: (optional) flags for the reg exp (like i for case insensitive
                "letters_only" - field must only contains letters (a-Z)

                "length=X"     - field has to be X characters long
                "length=X-Y"   - field has to be between X and Y (inclusive) characters long
                "length>X"     - field has to be greater than X characters long
                "length>=X"    - field has to be greater than or equal to X characters long
                "length<X"     - field has to be less than X characters long
                "length<=X"    - field has to be less than or equal to X characters long

                "valid_email"  - field has to be valid email address
                "valid_date"   - field has to be a valid date
                      fieldname:  MONTH 
                      fieldname2: DAY 
                      fieldname3: YEAR
                      date_flag:  "later_date" / "any_date"
                "same_as"     - fieldname is the same as fieldname2 (for password comparison)

                "range=X-Y"    - field must be a number between the range of X and Y inclusive
                "range>X"      - field must be a number greater than X
                "range>=X"     - field must be a number greater than or equal to X
                "range<X"      - field must be a number less than X
                "range<=X"     - field must be a number less than or equal to X

  
  Comments:   With both digits_only, valid_email and is_alpha options, if the empty string is passed 
              in it won't generate an error, thus allowing validation of non-required fields. So,
              for example, if you want a field to be a valid email address, provide validation for 
              both "required" and "valid_email".
\*--------------------------------------------------------------------------------------------*/
function validateFields($fields, $rules)
{ 
  $errors = array();
  
  // loop through rules
  for ($i=0; $i<count($rules); $i++)
  {
    // split row into component parts 
    $row = explode(",", $rules[$i]);
    
    // while the row begins with "if:..." test the condition. If true, strip the if:..., part and 
    // continue evaluating the rest of the line. Keep repeating this while the line begins with an 
    // if-condition. If it fails any of the conditions, don't bother validating the rest of the line
    $satisfies_if_conditions = true;
    while (preg_match("/^if:/", $row[0]))
    {
      $condition = preg_replace("/^if:/", "", $row[0]);

      // check if it's a = or != test
      $comparison = "equal";
      $parts = array();
      if (preg_match("/!=/", $condition))
      {
        $parts = explode("!=", $condition);
        $comparison = "not_equal";
      }
      else 
        $parts = explode("=", $condition);

      $field_to_check = $parts[0];
      $value_to_check = $parts[1];
      
      // if the VALUE is NOT the same, we don't need to validate this field. Return.
      if ($comparison == "equal" && $fields[$field_to_check] != $value_to_check)
      {
        $satisfies_if_conditions = false;
        break;
      }
      else if ($comparison == "not_equal" && $fields[$field_to_check] == $value_to_check)
      {
        $satisfies_if_conditions = false;
        break;      
      }
      else 
        array_shift($row);    // remove this if-condition from line, and continue validating line
    }

    if (!$satisfies_if_conditions)
      continue;


    $requirement = $row[0];
    $field_name  = $row[1];

    // depending on the validation test, store the incoming strings for use later...
    if (count($row) == 6)        // valid_date
    {
      $field_name2   = $row[2];
      $field_name3   = $row[3];
      $date_flag     = $row[4];
      $error_message = $row[5];
    }
    else if (count($row) == 5)     // reg_exp (WITH flags like g, i, m)
    {
      $field_name2   = $row[2];
      $field_name3   = $row[3];
      $error_message = $row[4];
    }
    else if (count($row) == 4)     // same_as, custom_alpha, reg_exp (without flags like g, i, m)
    {
      $field_name2   = $row[2];
      $error_message = $row[3];
    }
    else
      $error_message = $row[2];    // everything else!


    // if the requirement is "length=...", rename requirement to "length" for switch statement
    if (preg_match("/^length/", $requirement))
    {
      $length_requirements = $requirement;
      $requirement         = "length";
    }

    // if the requirement is "range=...", rename requirement to "range" for switch statement
    if (preg_match("/^range/", $requirement))
    {
      $range_requirements = $requirement;
      $requirement        = "range";
    }


    // now, validate whatever is required of the field
    switch ($requirement)
    {
      case "required":
        if (!isset($fields[$field_name]) || $fields[$field_name] == "")
          $errors[] = $error_message;
        break;

      case "digits_only":       
        if (isset($fields[$field_name]) && preg_match("/\D/", $fields[$field_name]))
          $errors[] = $error_message;
        break;

      case "letters_only": 
        if (isset($fields[$field_name]) && preg_match("/[^a-zA-Z]/", $fields[$field_name]))
          $errors[] = $error_message;
        break;

      // doesn't fail if field is empty
      case "valid_email":
                $regexp="/^[a-z0-9]+([_+\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";    
        if (isset($fields[$field_name]) && !empty($fields[$field_name]) && !preg_match($regexp, $fields[$field_name]))
          $errors[] = $error_message;
        break;

      case "length":
        $comparison_rule = "";
        $rule_string     = "";

        if      (preg_match("/length=/", $length_requirements))
        {
          $comparison_rule = "equal";
          $rule_string = preg_replace("/length=/", "", $length_requirements);
        }
        else if (preg_match("/length>=/", $length_requirements))
        {
          $comparison_rule = "greater_than_or_equal";
          $rule_string = preg_replace("/length>=/", "", $length_requirements);
        }
        else if (preg_match("/length<=/", $length_requirements))
        {
          $comparison_rule = "less_than_or_equal";
          $rule_string = preg_replace("/length<=/", "", $length_requirements);
        }
        else if (preg_match("/length>/", $length_requirements))
        {
          $comparison_rule = "greater_than";
          $rule_string = preg_replace("/length>/", "", $length_requirements);
        }
        else if (preg_match("/length</", $length_requirements))
        {
          $comparison_rule = "less_than";
          $rule_string = preg_replace("/length</", "", $length_requirements);
        }

        switch ($comparison_rule)
        {
          case "greater_than_or_equal":
            if (!(strlen($fields[$field_name]) >= $rule_string))
              $errors[] = $error_message;
            break;
          case "less_than_or_equal":
            if (!(strlen($fields[$field_name]) <= $rule_string))
              $errors[] = $error_message;
            break;
          case "greater_than":
            if (!(strlen($fields[$field_name]) > $rule_string))
              $errors[] = $error_message;
            break;
          case "less_than":
            if (!(strlen($fields[$field_name]) < $rule_string))
              $errors[] = $error_message;
            break;
          case "equal":
            // if the user supplied two length fields, make sure the field is within that range
            if (preg_match("/-/", $rule_string))
            {
              list($start, $end) = explode("-", $rule_string);
              if (strlen($fields[$field_name]) < $start || strlen($fields[$field_name]) > $end)
                $errors[] = $error_message;
            }
            // otherwise, check it's EXACTLY the size the user specified 
            else
            {
              if (strlen($fields[$field_name]) != $rule_string)
                $errors[] = $error_message;
            }     
            break;       
        }
        break;

      case "range":
        $comparison_rule = "";
        $rule_string     = "";

        if      (preg_match("/range=/", $range_requirements))
        {
          $comparison_rule = "equal";
          $rule_string = preg_replace("/range=/", "", $range_requirements);
        }
        else if (preg_match("/range>=/", $range_requirements))
        {
          $comparison_rule = "greater_than_or_equal";
          $rule_string = preg_replace("/range>=/", "", $range_requirements);
        }
        else if (preg_match("/range<=/", $range_requirements))
        {
          $comparison_rule = "less_than_or_equal";
          $rule_string = preg_replace("/range<=/", "", $range_requirements);
        }
        else if (preg_match("/range>/", $range_requirements))
        {
          $comparison_rule = "greater_than";
          $rule_string = preg_replace("/range>/", "", $range_requirements);
        }
        else if (preg_match("/range</", $range_requirements))
        {
          $comparison_rule = "less_than";
          $rule_string = preg_replace("/range</", "", $range_requirements);
        }
        
        switch ($comparison_rule)
        {
          case "greater_than":
            if (!($fields[$field_name] > $rule_string))
              $errors[] = $error_message;
            break;
          case "less_than":
            if (!($fields[$field_name] < $rule_string))
              $errors[] = $error_message;
            break;
          case "greater_than_or_equal":
            if (!($fields[$field_name] >= $rule_string))
              $errors[] = $error_message;
            break;
          case "less_than_or_equal":
            if (!($fields[$field_name] <= $rule_string))
              $errors[] = $error_message;
            break;
          case "equal":
            list($start, $end) = explode("-", $rule_string);

            if (($fields[$field_name] < $start) || ($fields[$field_name] > $end))
              $errors[] = $error_message;
            break;
        }
        break;
        
      case "same_as":
        if ($fields[$field_name] != $fields[$field_name2])
          $errors[] = $error_message;
        break;

      case "valid_date":
        // this is written for future extensibility of isValidDate function to allow 
        // checking for dates BEFORE today, AFTER today, IS today and ANY day.
        $is_later_date = false;
        if    ($date_flag == "later_date")
          $is_later_date = true;
        else if ($date_flag == "any_date")
          $is_later_date = false;

        if (!is_valid_date($fields[$field_name], $fields[$field_name2], $fields[$field_name3], $is_later_date))
          $errors[] = $error_message;
        break;

      case "is_alpha":
        if (preg_match('/[^A-Za-z0-9]/', $fields[$field_name]))
          $errors[] = $error_message; 
        break;
        
      case "custom_alpha":
        $chars = array();
        $chars["L"] = "[A-Z]";
        $chars["V"] = "[AEIOU]";
        $chars["l"] = "[a-z]";
        $chars["v"] = "[aeiou]";
        $chars["D"] = "[a-zA-Z]";
        $chars["F"] = "[aeiouAEIOU]";
        $chars["C"] = "[bCDFGHJKLMNPQRSTVWXYZ]";
        $chars["x"] = "[0-9]";
        $chars["c"] = "[bcdfghjklmnpqrstvwxyz]";
        $chars["X"] = "[1-9]";
        $chars["E"] = "[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]";

        $reg_exp_str = "";
        for ($j=0; $j<strlen($field_name2); $j++)
        {
          if (array_key_exists($field_name2[$j], $chars))
            $reg_exp_str .= $chars[$field_name2[$j]];
          else
            $reg_exp_str .= $field_name2[$j];
        }

        if (!empty($fields[$field_name]) && !preg_match("/$reg_exp_str/", $fields[$field_name]))
          $errors[] = $error_message;
        break;

      case "reg_exp":
        $reg_exp_str = $field_name2;

        // rather crumby, but...
        if (count($row) == 5)
          $reg_exp = "/" . $reg_exp_str . "/" . $row[3]; 
        else
          $reg_exp = "/" . $reg_exp_str . "/"; 

        if (!empty($fields[$field_name]) && !preg_match($reg_exp, $fields[$field_name]))
          $errors[] = $error_message;
        break;

      default:
        die("Unknown requirement flag in validate_fields(): $requirement");
        break;
    }
  }
  
  return $errors;
}


/*------------------------------------------------------------------------------------------------*\
  Function:   is_valid_date
  Purpose:    checks a date is valid / is later than current date
  Parameters: $month       - an integer between 1 and 12
              $day         - an integer between 1 and 31 (depending on month)
              $year        - a 4-digit integer value
              $is_later_date - a boolean value. If true, the function verifies the date being passed 
                               in is LATER than the current date.
\*------------------------------------------------------------------------------------------------*/
function is_valid_date($month, $day, $year, $is_later_date)
{
  // depending on the year, calculate the number of days in the month
  if ($year % 4 == 0)      // LEAP YEAR 
    $days_in_month = array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  else
    $days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);


  // first, check the incoming month and year are valid. 
  if (!$month || !$day || !$year) return false;
  if (1 > $month || $month > 12)  return false;
  if ($year < 0)                  return false;
  if (1 > $day || $day > $days_in_month[$month-1]) return false;


  // if required, verify the incoming date is LATER than the current date.
  if ($is_later_date)
  {    
    // get current date
    $today = date("U");
    $date = mktime(0, 0, 0, $month, $day, $year);
    if ($date < $today)
      return false;
  }

  return true;
}

?>

Also Here can see demo is setup on website http://www.benjaminkeen.com/software/php_validation/demo.php

This Is for what i was looking for but now only must figure out how to make work for my use :)

Link to comment
Share on other sites

Hi Everybody i am trying to integrate the code but it's not working as i were expecting when press button submit it shows message to fill area but still it's sending a blank form into dabase i think i am something missing i hope to see solution in this problem .

if (isset($_POST['pievienot']))
{
    // import the validation library
  require("validation.php");

  $rules = array(); // stores the validation rules

  // standard form fields
  $rules[] = "required,text,This field is required.";
  
  $errors = validateFields($_POST, $rules);

  // if there were errors, re-populate the form fields
  if (!empty($errors))
  {  
    $fields = $_POST;
  }
  
  // no errors! redirect the user to the thankyou page (or whatever)
  else 
  {
    $message = "All fields have been validated successfully!";
    
    // here you would either email the form contents to someone or store it in a database. 
    // To redirect to a "thankyou" page, you'd just do this:
    // header("Location: thanks.php");
  }    
    
    $text = mysql_real_escape_string($_POST[text]);
    $text = htmlentities($_POST[text]);
    $text = trim($_POST[text]);
    $id   = (int)$_GET['id'];

    $insert = "INSERT INTO comment (comment_name,comment_datetime,comment_text,news_id,comment_ip) VALUES ('".$_SESSION['u_nick']."',NOW(),'".$text."','".$id."','".$ip."')";
    mysql_query($insert) or die(mysql_error());
    
}

    if (!empty($errors))
    {
      echo "<div class='error' style='width:100%;'>Please fix the following errors:\n<ul>";
      foreach ($errors as $error)
        echo "<li>$error</li>\n";
    
      echo "</ul></div>"; 
    }
    
    if (!empty($message))
    {
      echo "<div class='notify'>$success_message</div>";
    }

echo ("
<h3>Pievienot Komentāru</h3>
<form method='post'>
Komentara Teksts : <br><textarea name='text' cols='40' rows='6' value='{$fields['text']}'></textarea><br>
<input type='submit'  name='pievienot' value='pievienot' />
</form>");

Link to comment
Share on other sites

I'm feeling exceptionally nice today.

 

Your problem is exactly where I said it was:

 

$text = mysql_real_escape_string($_POST[text]); // text is an undefined constant, therefor $text has not been given a value
    $text = htmlentities($_POST[text]); // text is still an undefined constant, therefor $text has STILL NOT BEEN GIVEN A VALUE
    $text = trim($_POST[text]); // Well! What do you know! text is an undefined constant, therefor $text has STILL NOT BEEN GIVEN A VALUE, noticing a pattern yet?

Because it's not defined properly, your SQL syntax looks like this:

 

$insert = "INSERT INTO comment (comment_name,comment_datetime,comment_text,news_id,comment_ip) VALUES ('".$_SESSION['u_nick']."',NOW(),'','".$id."','".$ip."')";

It looks like this because $text contains no string:

 

echo '" '.$text.' "'; // this would echo: "  " because you didn't put any text into the variable $text
echo strlen($text); // this would echo: 0 because $text has no string in it, it's just an empty variable

 

Also, you're not formatting the string properly, you keep overriding the previous formats when you try to reassign $text. You might try this if you actually want to get it to work.

 

MY SOLUTION:

$text = mysql_real_escape_string(htmlentities(trim($_POST['text'])));

 

If it's not blatantly obvious, look at the color of the word "text" in the $_POST index when I copied your code, and look at it when I modified your code, see the difference? One is a constant (yours, and I imagine you haven't defined it) and one is a string (mine). You're looking for the index that has the string "text" so mine will probably work, while yours is obviously not working.

 

I don't mean to be mean but here's the thing, you came here looking for help from people who volunteer their time through their own good will. If you're going to turn around and complain about the answers they give you while not even trying them to see if they work, why should we be bothered to waste our time helping you?

 

I gave you your answer yesterday, perhaps if you had been grateful enough to try it your program would be working now. I highly suggest you at least try my solution now, I guarantee you it can't be any worse than what your program is currently doing.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.