1

I have been trying to use PHP to validate my form.

The form asks users to enter details which will then get entered into a table in a database once the form has been validated.

I have a customer ID field in the form, and I am trying to validate it to make sure that it has a value (compulsory field), contains only numeric characters, is exactly 6 digits in length and is a unique ID (i.e. does not already exist in the database).

Here is what I have so far :

<body>

<?php
$temp = "";
$msg = "";
$rst = "";

if (isset($_POST["submit"])) {  
$number = $_POST["custid"];

if(empty($number)) {
$msg = '<span class="error"> Please enter a value</span>';
} else if(!is_numeric($number)) {
$msg = '<span class="error"> Data entered was not numeric</span>';
} else if(strlen($number) != 6) {
$msg = '<span class="error"> The number entered was not 6 digits long</span>';
} else {
echo "valid";
}

}

?>

<h1>Customer Information Collection <br /></h1>

<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="custinfo" >
<table>
<tr>
    <td><label for="custid">Customer ID (integer value): </label></td>
    <td><input type="text" id="custid" name="custid" value="<?php echo   $temp ?>" size=11 /><?php echo $msg; ?></td>
</tr>

<tr>
    <td><label for="customerfname">Customer Frist Name: </label></td>
    <td><input type="text" id="customerfname" name="fname" size=50/></td>
</tr>
<tr>
    <td><label for="customerlname">Customer Last Name: </label></td>
    <td><input type="text" id="customerlname" name="lname" size=50/></td>
</tr>
<tr>
    <td><label for="customeraddress">Customer Address: </label></td>
    <td><input type="text" id="customeraddress" name="custaddress" size=65/></td>

    <td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td>
State:<select name="state" id="state">
    <option value="select">--</option>
    <option value="ACT">ACT</option>
    <option value="NSW">NSW</option>
    <option value="NT">NT</option>
    <option value="QLD">QLD</option>
    <option value="SA">SA</option>
    <option value="TAS">TAS</option>
    <option value="VIC">VIC</option>
     <option value="WA">WA</option>
  </select>
</td>
<td><label for="postcode"> Post Code: </label><input type="text" id="postcode" name="postcode" size=4/></td>
</tr>
</table>
<p><input type="submit" name="submit" value="Save Data"/>&nbsp;<input type="reset" value="Clear Form" />
</tr>

</form>

</body> 

The problem I am having is that when I purposely enter incorrect values into the customer ID field, it doesn't give me any error. It just processes the incorrect values as if they were correct.

Any help would be really great! If any more information is needed, just ask.

Warren Sergent
  • 2,542
  • 4
  • 36
  • 42
user2273149
  • 29
  • 1
  • 2
  • 7
  • this could help you.. http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric – reikyoushin May 03 '13 at 15:07
  • @reikyoushin - read the question – Ryan May 03 '13 at 15:08
  • Isn't my if ($number < 6 || $number > 6){ the correct condition to check if it has 6 digits? – user2273149 May 03 '13 at 15:11
  • No - it should be strlen - read my answer – Ryan May 03 '13 at 15:11
  • Wouldn't it be easier to generate the customer ID yourself, using an auto-increment field in the database? – andrewsi May 03 '13 at 15:12
  • @andrewsi it could be a reference to an existing customer – Ryan May 03 '13 at 15:14
  • `$number < 6` checks if the number is below 6, like 1, 2 or 4, and not the length, and as anything returned from $_POST would be a string, string methods are the way to go. – adeneo May 03 '13 at 15:15
  • @Stanyer - it could. But then you wouldn't need to validate it was in the right format - you could just check to see if it's in the database. – andrewsi May 03 '13 at 15:16
  • What you really should be using is `FILTER_VALIDATE_INT` with a range. – adeneo May 03 '13 at 15:19
  • @andrewsi - May aswell validate the form before querying MySQL. Although probably not in this case, it would be more efficient to check the data is at least in the correct format before running a MySQL query on incorrect data as if it was a popular application it could create unnecessary MySQL overhead. Also - OP's process may not even use a database – Ryan May 03 '13 at 15:20
  • You do realize that the name of the element in the form is `custid` and not `customerid`, so you would have to use `$_POST['custid']` to even get a number ? – adeneo May 03 '13 at 15:27
  • Thank you for pointing that out for me it was driving me insane, i always forget to change my variable names. – user2273149 May 03 '13 at 15:33

4 Answers4

12

Here is your validation simplified, and with the correct operation to check the length of the id.

if(empty($number)) {
    $msg = '<span class="error"> Please enter a value</span>';
} else if(!is_numeric($number)) {
    $msg = '<span class="error"> Data entered was not numeric</span>';
} else if(strlen($number) != 6) {
    $msg = '<span class="error"> The number entered was not 6 digits long</span>';
} else {
    /* Success */
}
Ryan
  • 3,552
  • 1
  • 22
  • 39
  • Your answer does seem correct but for some reason my form just isn't returning any errors when i purposely enter incorrect values, it just processes it. – user2273149 May 03 '13 at 15:19
  • oh wow sorry i had set it to echo $tempmsg instead of $msg but i have changed that now, it is now displaying an error but it only diplays "Please enter a value" whenever i enter any sort of value including the correct values. – user2273149 May 03 '13 at 15:24
  • Oh wait i have fixed it, it was just a case of incorrect labeling of variables. Thank you for all the help! – user2273149 May 03 '13 at 15:29
0

In your case this is happening.

1) Checking empty string

2) Cheking numeric string and if it is numeric then checking the length.

Even after your validation fails for example if you enter invalid details, your validation captures the error and put it in $msg variable, but now your are not using that $msg variable if you echo that variable you can verify that it is working fine or not.

Hence do

echo $msg; 

to verify your validation.

chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
0
if (isset($_POST['add-contact'])) {

    $addPhone= $_POST['phone_no'];
    $addCell = $_POST['cell_no'];
    $addEmail= $_POST['email_address'];

    $addPhone = trim($addPhone);
    $addCell = trim($addCell);
    $addEmail = trim($addEmail);


    if (empty($addPhone) && empty($addCell) && empty($addEmail)) {
        message("danger","At least one field is required...");
    } elseif (strlen($addPhone) > 13) {
        message("danger","Phone No length is too large greater then 13...");
    } elseif (strlen($addCell) > 15) {
        message("danger","Cell No length is too large greater then 15...");
    } elseif (!is_numeric($addPhone)) {
        message("danger","Invalid phone no ,only numbers are allowed..");
    } elseif (!is_numeric($addCell)) {
        message("danger","Invalid cell no ,only numbers are allowed..");
    } else {
        $q = "insert into contact_tbl(phone_no,cell_no,email)values('$addPhone','$addCell','$addEmail')";
        mysql_query($q, $connect);
        message("info", "Contact details added successfully...");
    }
}
nikc.org
  • 16,462
  • 6
  • 50
  • 83
rizwan
  • 1
0

Here is the full solution with numeric-only and also you can specify the length of numbers

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
    $data = mysql_real_escape_string($data);
  return $data;
}  

if (is_numeric($_POST['emergency_num'])) {
          
      $emergency_num = test_input($_POST['emergency_num']);
        
       if(strlen($emergency_num) < 9){
              $errormsg = "Emergency Number can not be less than 9 digits Please Enter Correct number";
          }
      } else {
        $errormsg = 'Error: Please enter only numbers in Emergency Contact Number.';
        }
Hassan Qasim
  • 463
  • 5
  • 5