Jump to content
SkyRanger

Validation Question

Recommended Posts

I am working on a form validation script and not sure how to approach this.  I can validate current entries that are required but I am trying to figure out how to validate an entry only if submitted and ignored if field is empty.

/*form field*/
<input type="text" name="account">
<?php
echo "<div class='note'>".$msg_acct."<br/>";



/*This is in the validation script*/
if(empty($_POST['account']))
$acct_subject = $_POST['account'];
$acct_pattern = '/^[0-9]*$/';
preg_match($acct_subject, $aact_matches);
if(!$acct_matches[0])
$msg_acct = "Only numbers are allowed";

 

Share this post


Link to post
Share on other sites
Posted (edited)

It looks like your validation script makes zero sense, but it's hard to tell without braces and/or correct indentation. But it certainly looks like the first thing you do is attempt to assign $_POST['account'] to $acct_subject if and only if $_POST['account'] is empty.

Edited by maxxd
can't spell

Share this post


Link to post
Share on other sites

Sorry maxxd

 if( isset($_POST['submit']) )
    {

    if(empty($_POST['kudoagent']))
$msg_name = "You must supply agent name";
$name_subject = $_POST['kudoagent'];
$name_pattern = '/^[a-zA-Z ]*$/';
preg_match($name_pattern, $name_subject, $name_matches);
if(!$name_matches[0])
$msg2_name = "Only alphabets and white space allowed";

    if(empty($_POST['agentloc']))
$msg_agloc = "You must select a location";

    if(empty($_POST['kudoclient']))
$msg_kclient = "You must select a queue";

    if(empty($_POST['kudocust']))
$msg_custname = "You must supply customer name";
$custname_subject = $_POST['kudocust'];
$custname_pattern = '/^[a-zA-Z ]*$/';
preg_match($custname_pattern, $custname_subject, $custname_matches);
if(!$custname_matches[0])
$msg2_custname = "Only alphabets and white space allowed";

/*This is the issue part*/
	
	if(empty($_POST['account']))
$acct_subject = $_POST['account'];
$acct_pattern = '/^[0-9]*$/';
preg_match($acct_subject, $aact_matches);
if(!$acct_matches[0])
$msg_acct = "Only numbers are allowed";

/*end of issue part*/

    if(empty($_POST['kudomsg']))
$msg_kmsg = "You must enter a kudos";

}

    if(isset($_POST['submit'])){
    if($msg_name=="" && $msg2_name=="" && $msg_agloc=="" && $msg_kclient=="" && $msg_custname=="" && $msg2_custname=="" && $msg_kmsg=="" && msg_acct=="")
    $msg_success = "Kudos has been submitted";

 

Share this post


Link to post
Share on other sites

Simpler...

if (isset($_POST['account']) && ctype_digit($_POST['account'])) {
    // OK
}
else {
    // ERROR
}

 

Share this post


Link to post
Share on other sites

Run in to a new issue and still having issue with code advised of Barand.  Even if there are errors the info is still submitting to database and if somebody does not enter anything in the account field it is stating that is required.

 if( isset($_POST['submit']) )
    {

    if(empty($_POST['kudoagent']))
$msg_name = "You must supply agent name";
$name_subject = $_POST['kudoagent'];
$name_pattern = '/^[a-zA-Z ]*$/';
preg_match($name_pattern, $name_subject, $name_matches);
if(!$name_matches[0])
$msg2_name = "Only alphabets and white space allowed";

    if(empty($_POST['agentloc']))
$msg_agloc = "You must select a location";

    if(empty($_POST['kudoclient']))
$msg_kclient = "You must select a queue";

    if(empty($_POST['kudocust']))
$msg_custname = "You must supply customer name";
$custname_subject = $_POST['kudocust'];
$custname_pattern = '/^[a-zA-Z ]*$/';
preg_match($custname_pattern, $custname_subject, $custname_matches);
if(!$custname_matches[0])
$msg2_custname = "Only alphabets and white space allowed";

    if(empty($_POST['kudomsg']))
$msg_kmsg = "You must enter a kudos";

    if (isset($_POST['account']) && ctype_digit($_POST['account'])) {
    // Nothing to output
}
else {
    // ERROR
  $msg = "Only number are permitted";
}

}

    if(isset($_POST['submit'])){
    if($msg_name=="" && $msg2_name=="" && $msg_agloc=="" && $msg_kclient=="" && $msg_custname=="" && $msg2_custname=="" && $msg_kmsg=="")
    $msg_success = "Kudos has been submitted";

     global $wpdb;
            $table = $tablename;
            $kudokey = randkey();
            $kudoposted = date("Y-m-d H:i:s");
            $data = array(
                'kudoid' => '',
                'kudomsg'    => $_POST['kudomsg'],
                'kudoagent' => $_POST['kudoagent'],
                'kudoagentid' => $_POST['kudoagentid'],
                'kudocust'    => $_POST['kudocust'],
                'kudoacct' => $_POST['kudoacct'],
                'kudoclient'    => $_POST['kudoclient'],
                'kudoloc' => $_POST['agentloc'],
                'kudoentry'    => $kudoposted,
                'kudoadmin'    => $_POST['kudoadmin'],
                'kudopic'     => $_POST['kudobanner'],
                'kudostatus'   => '0',
     			'kudokey'  => $kudokey,
            );
            $format = array(
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s'
            );
            $success=$wpdb->insert( $table, $data, $format );
            if($success){
        /*
        echo "<blockquote class=\"otro-blockquote\">";
		echo nl2br($_POST['kudomsg']);
		echo "<span>";
		echo "<b>Kudos for:</b> " .$_POST['kudoagent']. " - " .$_POST['kudoagentid']. ", ".$_POST['agentloc'];
  		echo "<br>By: ".$_POST['kudocust']. ", " . date("F j, Y g:i a", strtotime($kudoposted));
  		echo "<br/>" .$_POST['kudoacct'];
  		echo "<br/> Submitted By: " .$_POST['kudoadmin'];
		echo "</span></blockquote>";
		$urlparts = parse_url(home_url());
        $kudourl = $urlparts['host'];
        */

         echo "<div class='success_msg'>".$msg_success."</div>";

         }

        }

 

Share this post


Link to post
Share on other sites

1. Stop with the random use of curly braces. Just use them always.

2. Get rid of the redundant submit check. You should be checking the REQUEST METHOD anyways. Checking for submit can fail in certain cases.

3. Stop creating variables for nothing.

4. The errors should go in an errors array.

5. Your code gives a success message for submitting an empty form. That makes no sense.

6. There is nothing that stops the DB insert since you do nothing with the errors.

Share this post


Link to post
Share on other sites

i reviewed one of your earlier threads and it was using an array to hold errors. what happened, why did you take a step backwards?

your existing validation logic for a 'required' field is not doing what you think, so, when you copied it for a non-required field, it has no chance of working.

for a required field, if the input is empty, that's an error and there's no point in running any additional validation on that input as they will fail too. only if the input is not empty, run additional validation on that input. the logic to do this would look like -

if(some required field == '') // note the comparision is with an emtpy string. php's empty() treats a zero as empty, so if zero is a valid value, you don't want to use empty() to test it.
{
	// the field is an empty string
	$errors['some field name'] = "This field is required.";
}
else
{
	// the field is not empty, perform additional validation step(s)
	if(!some other validation test) // note the ! (not) in the conditional statement
	{
		// the field did not pass this validtion test
	    $errors['some field name'] = "This field does not meet the requirements of this validtion test.";
	}
}

 

for a non-required field, you don't care if the field is empty, but if it is not empty, you perform the additional validation (this is basically the else logic from above) -

if(some field != '')
{
	// the field is not empty, perform additional validation step(s)
	if(!some other validation test) // note the ! (not) in the conditional statement
	{
		// the field did not pass this validtion test
		$errors['some field name'] = "This field does not meet the requirements of this validtion test.";
	}
}

if all you are doing with preg_match is finding if a value matches the pattern, there's no need for the matches parameter. just directly test the result of the preg_match statement.

your original validation logic for the account field contained miss-typed variables and incorrect preg_match parameters. do you have php's error_reporting set to E_ALL and display_errors set to ON so that php would help you by reporting and displaying all the errors it detects?

lastly, when you have more than about 2-3 form fields, you should dynamically process the form data, by defining an array that holds a definition of the fields and what validation tests to perform on each field. this is a level to work toward in your coding, so that you don't find yourself writing out bespoke logic for each form field for each different form.

Share this post


Link to post
Share on other sites

Hi mac_gyver. For some reason not sure what happened with that script. It actually is(was) working in another part of my plugin but for some reason not sure if I typed something wrong in the new part of the program.  I squashed the latest validation check above as it was causing nightmares.  I am currently working on securing the validation as I got it working almost the way it is needed but still having a problem with one field.  The account one that barand has provided assistance on.  person leaves account field empty should not give error. When enters data into field check field to ensure they are only numbers.

if (isset($_POST['account']) && ctype_digit($_POST['account'])) {
    // OK
}
else {
    $accountErr = "Only numbers are permitted or leave blank";
}

 

Share this post


Link to post
Share on other sites
7 minutes ago, SkyRanger said:

person leaves account field empty should not give error. When enters data into field check field to ensure they are only numbers.

In that case

if (isset($_POST['account']) && trim($_POST['account']) != '' && !ctype_digit($_POST['account'])) {
    $accountErr = "Only numbers are permitted or leave blank";
}
else {
    $accountErr = "";
}

 

Share this post


Link to post
Share on other sites

I'm not going to bother even reading through your code. You need to STOP, take a breath, and come up with a logical, repeatable process for form validations. Here is an example of the start of a process you could follow:

 

<?php
	//Create arrays of valid values for fields using a 'list' (e.g. select, radio group, etc.)
// - the array index represents the value
// - the array value represents the label
// This could be created from a DB query if the lookups are stored there.
// Use this for BOTH the validation AND for creating the select list, radio group, etc.
// FYI: You can't assume the value passed for a select list is one you provided!!!
$field4Values = array(
  1 => "Blue",
  2 => "Green",
  3 => "Red",
  4 => "Yellow"
);
	//Create array to hold the errors
$errors = array();
	//Check if form was submitted
// I usually have form pages submit to themselves so I can repopulate fields
// if there are errors. So, should only do validations if the form was submitted
if($_SERVER['REQUEST_METHOD']=='POST')
{
    //Trim all the post values
    // You have to determine if this is appropriate (can some legitimate value have 
    // beginning/ending whitespace?). Also, can't use array_map like this if the
    // post fields contain multi-dimensional arrays
    array_map('trim', $_POST);
	    
    //Validate the fields
    
    //Field is required
    if($_POST['field1']$_POST['field1']=='')
    {
        $errors['field1'] = "Field 1 is required";
    }
    
    //Field is NOT required, but must be a number
    if($_POST['field2']!='' && )
    {
        $errors['field1'] = "Field 2 must be a number";
    }
	    //Field IS required, and must be a number
    if($_POST['field3']=='')
    {
        $errors['field3'] = "Field 3 is required";
    }
    elseif(!ctype_digit($_POST['field3']))
    {
        $errors['field3'] = "Field 3 must be a number";
    }
    
    //Field must contain a values in a predetermined list
    if(!array_key_exists($errors['field4'], $field4Values))
    {
        $errors['field3'] = "Field 4 is not a valid color";
    }
	    // And so on, and so on
    //Create 'helper' functions for more complicated validations:
   
    //Validation process complete - see if there were errors
    if(empty($errors))
    {
        //Add logic to process the form data - e.g. database insert/update
        //Redirect to another page: e.g. update successful, listing, etc.
        //Read up on PRG - (Post, Redirect, Get) for form processing
        header('http://mydomain.com/formsuccess.php');
        exit();
    }
    
    //If there were errors, code continues to form display logic
}
	//Include the code to display the form
//This should display the errors if any exist
//and populate any fields with previously POSTed values
include('formpage.php');
	?>

Share this post


Link to post
Share on other sites

Thanks all for your help got it working and a special thanks again to barand, worked like I needed it to.

Share this post


Link to post
Share on other sites

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.