Jump to content

Archived

This topic is now archived and is closed to further replies.

artemisbow

Form Checking (Missing Inputs)

Recommended Posts

Hi, I'm using the following code to check that the form has been filled up completely
[code]if((!value1) || (!value2)... || (!valueX)){
  echo "Some fields have not been filled in";
  }
[/code]

However, when a user enters '0', I want the script to know that it is not empty, but neither the above method nor using empty() works. What should I do instead? Thanks!

Share this post


Link to post
Share on other sites
You could use regular expressions.
[code]
function isValidInput( $str )
{
    // Test for a zero, null, or empty string
    if( !ereg( "^[a-zA-Z]$", $str ) || empty( $str ) || ! isset( $str ) || ( $str < 1 ) )
        return false;    
}
[/code]

Now you can get creative and check for ranges or specific patterns. For example postal codes:
[code]
$pcode=str_replace(" ","",$in_post_code);
if (!ereg('^[a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]{0,1}[0-9]{1}[a-zA-Z]{2}$', $pcode))
{
   return false;
}
[/code]

Check out www.php.net for additional information on php functions that might be helpful to you.

Regards,

ProdyneTech

[!--quoteo(post=371765:date=May 6 2006, 12:48 AM:name=artemisbow)--][div class=\'quotetop\']QUOTE(artemisbow @ May 6 2006, 12:48 AM) [snapback]371765[/snapback][/div][div class=\'quotemain\'][!--quotec--]
Hi, I'm using the following code to check that the form has been filled up completely
[code]if((!value1) || (!value2)... || (!valueX)){
  echo "Some fields have not been filled in";
  }
[/code]

However, when a user enters '0', I want the script to know that it is not empty, but neither the above method nor using empty() works. What should I do instead? Thanks!
[/quote]

Share this post


Link to post
Share on other sites
What you need to do is actually test each field to make sure that something was entered:
[code]<?php
$errs = array();
foreach ($_POST as $key => $val)
    if ($key != 'submit')  // I'm assuming that the submit button in your form is named 'submit'
       if (strlen(trim(stripslashes($val))) == 0) // Is the field truly empty  -- strlen is 0
             $errs[] = $k;
if (!empty($errs)) // if the $errs array is not empty, at least one field was left blank
   echo 'The following fields were left blank:<br><span style="color:red">' . implode('<br>',$errs) . '</span>';
?>[/code]

Ken

Share this post


Link to post
Share on other sites

×

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.