Link to home
Start Free TrialLog in
Avatar of Colin Brazier
Colin BrazierFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Validate against carriage returns in a textarea

Hi experts,

I have a textarea in a form.  I validate that this should not be empty, i.e. it must have some visible input.

I can break the validation simply by hitting the Enter key, thus putting a carriage return in an apparently blank field, will be accepted as valid.

How do I get around this?

My current code:
$temp = trim($_POST[$fields[$key]['form_name']]);  // Translates to eg. $temp = trim($_POST['txtBookTitle'])  
	
if (empty($temp) )
{
	$error_array[] = $fields[$key]['message'];
	${$key} = '';
}

Open in new window

SOLUTION
Avatar of Ferruccio Accalai
Ferruccio Accalai
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This does two things
1. Ensures that $_POST[$field...] contains only characters you expect (santisizes)
2. Makes sure that what is in the field matches what you expect (checks input valid)

$temp = isset($_POST[$fields[$key]['form_name']]) 
   ? preg_match('/\w+/', $_POST[$fields[$key]['form_name']]) 
   : false;

if ($temp)  {
   echo "Input is valid";
}
else {
   echo "input is invalid";
}

Open in new window

Avatar of Colin Brazier

ASKER

Thanks guys.

In all 3 cases, only putting carriage returns in passes the validation, whereas simple spaces doesn't.

This is on my PC (xampp) so I can't show an example.
Cannot help then.
Please make sure that your $fields[$key]['form_name'] does translate to the name of the textarea.
And maybe attach your both HTML and the PHP script here.  Maybe it's not the validation itself, but some code later than that.

Good luck!
I put the code above into a sample here. The sample demonstrates the code works.

HTML
    <form action="t1660.php" method="post">
		<textarea name="test"></textarea> <input type="submit" />
	</form>

Open in new window

PHP
<pre>
<?php
print_r($_POST);
$temp = isset($_POST['test']) 
   ? preg_match('/\w+/', $_POST['test']) 
   : false;

if ($temp) {
echo "ok";
} 
else {
echo "not ok";
}?>
</pre>

Open in new window

Another try (this should remove any new line even if it's empty)
$temp = trim(preg_replace('/\s+/', '', $_POST[$fields[$key]['form_name']]));  	
if ($temp == "")
{
	$error_array[] = $fields[$key]['message'];
	${$key} = '';
}

Open in new window

The problem with removing white space is instead of

This is my required response 

Open in new window


You get
Thisismyrequiredresponse

Open in new window


Not necessarily the desired outcome
@Not necessarily the desired outcome
Maybe that's why he's assigning it to a $temp variable just to check for validation.
I guess he uses a non trimmed $_POST value once validated.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yeah there's something funny going on here.

I've done my own simplified test script and testing for empty($temp)  and Julian's preg_match both work, though testing for $temp == '' following the trim() allows a blank textarea through.

I feel bad about using everyone's time on this, so let me get back to the original code and I'll try to see what's going on.

Cheers

<?php
if (isset($_POST['btnSubmit']))
{
	$temp = trim($_POST['btnSubmit']);  
	
	if ($temp == '')
	{
	   echo "Input is invalid";
	}
	else 
	{
	   echo "input is valid";
	}
	exit();
	// Allows anything through - all blanks are valid.
	
	
	/*if (empty($temp))
	{
	   echo "Input is valid";
	}
	else 
	{
	   echo "input is invalid";
	}
	exit();*/
	// Works - line breaks only are not valid
	
	
	/*$temp = isset($_POST['txtBody']) 
	   ? preg_match('/\w+/', $_POST['txtBody']) 
	   : false;
	
	if ($temp)  {
	   echo "Input is valid";
	}
	else {
	   echo "input is invalid";
	}
	exit();*/
	// Works - line breaks only are not valid
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
	<div id="maintenance_form" > 
    <form name="form1" id="form1" action="" method="post" enctype="multipart/form-data" >
        <fieldset> 
                <label for="txtBody" class="item_label">Body:</label>
                <textarea rows="4" cols="75" name="txtBody" maxlength="1000" ></textarea>
                <input type="submit" name="btnSubmit" id="btnSubmit" value="Save"  />
	            <input type="submit" name="btnCancel" id="btnCancel" value="Cancel"  />
		</fieldset>
    </form>
    </div> 
</body>
</html>

Open in new window

if (isset($_POST['btnSubmit']))

Open in new window

Why are you testing btnSubmit when your textarea name is txtBody
<textarea rows="4" cols="75" name="txtBody" maxlength="1000" ></textarea>

Open in new window

What does this do
<?php
if (isset($_POST['txtBody']))
{
	$temp = trim($_POST['txtBody']);  
	
	if ($temp == '')
	{
	   echo "Input is invalid";
	}
	else 
	{
	   echo "input is valid";
	}
	exit();
	// Allows anything through - all blanks are valid.
	
	
	/*if (empty($temp))
	{
	   echo "Input is valid";
	}
	else 
	{
	   echo "input is invalid";
	}
	exit();*/
	// Works - line breaks only are not valid
	
	
	/*$temp = isset($_POST['txtBody']) 
	   ? preg_match('/\w+/', $_POST['txtBody']) 
	   : false;
	
	if ($temp)  {
	   echo "Input is valid";
	}
	else {
	   echo "input is invalid";
	}
	exit();*/
	// Works - line breaks only are not valid
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
	<div id="maintenance_form" > 
    <form name="form1" id="form1" action="" method="post" enctype="multipart/form-data" >
        <fieldset> 
                <label for="txtBody" class="item_label">Body:</label>
                <textarea rows="4" cols="75" name="txtBody" maxlength="1000" ></textarea>
                <input type="submit" name="btnSubmit" id="btnSubmit" value="Save"  />
	            <input type="submit" name="btnCancel" id="btnCancel" value="Cancel"  />
		</fieldset>
    </form>
    </div> 
</body>
</html>

Open in new window

Seems to work in this sample
Trimming the button instead of the textarea - D'OH!

I now trim the textarea and test for it and all solutions work in my test.  I get input is valid 3 times if I just put white space in there.

<?php
if (isset($_POST['btnSubmit']))
{
	$temp = trim($_POST['txtBody']);  
	
	echo "temp == ''<br/>";
	if ($temp == '')
	{
	   echo "Input is invalid<br/>";
	}
	else 
	{
	   echo "input is valid<br/>";
	}
	// Works - line breaks only are not valid
	
	echo "empty(temp)<br/>";
	if (empty($temp))
	{
	   echo "Input is invalid<br/>";
	}
	else 
	{
	   echo "input is valid<br/>";
	}
	// Works - line breaks only are not valid
	
	echo "preg_match<br/>";
	$temp = isset($_POST['txtBody']) 
	   ? preg_match('/\w+/', $_POST['txtBody']) 
	   : false;
	
	if ($temp)  {
	   echo "Input is valid";
	}
	else {
	   echo "input is invalid";
	}
	exit();
	// Works - line breaks only are not valid
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
	<div id="maintenance_form" > 
    <form name="form1" id="form1" action="" method="post" enctype="multipart/form-data" >
        <fieldset> 
                <label for="txtBody" class="item_label">Body:</label>
                <textarea rows="4" cols="75" name="txtBody" maxlength="1000" ></textarea>
                <input type="submit" name="btnSubmit" id="btnSubmit" value="Save"  />
	            <input type="submit" name="btnCancel" id="btnCancel" value="Cancel"  />
		</fieldset>
    </form>
    </div> 
</body>
</html>

Open in new window

What does this do

Works correctly, results as expected.
This is my actual original code wherein lies the problem.
foreach ($fields as $key => $value)
	{
		if (isset($_POST[$fields[$key]['form_name']]))
		{
			$_POST[$fields[$key]['form_name']] = mysqli_real_escape_string($db->connection, $_POST[$fields[$key]['form_name']]);
			
			$temp = trim($_POST[$fields[$key]['form_name']]);  // Translates to eg. $temp = trim($_POST['txtBookTitle'])  
	
			if ($fields[$key]['required'] == 1)
			{
				$temp = isset($_POST[$fields[$key]['form_name']]) 
				   ? preg_match('/\w+/', $_POST[$fields[$key]['form_name']]) 
				   : false;
				
				if ($temp)  {
				   echo "Input is valid";
				}
				else {
				   echo "input is invalid";
				}
				exit();
			}

			/*if (empty($temp) && $fields[$key]['required'] == 1)
			{
				$error_array[] = $fields[$key]['message'];
				${$key} = '';
			}*/
		}
	}

Open in new window

The $fields array has these contents:
Array
(
    [body] => Array
        (
            [required] => 1
            [default_value] => 
            [form_name] => txtBody
            [type] => text
            [message] => Body must be entered
            [db_tablename] => pp_jobs
        )

    [pos_id] => Array
        (
            [required] => 0
            [default_value] => 0
            [form_name] => txtPosId
            [type] => text
            [message] => 
            [db_tablename] => pp_jobs
        )

    [stored_file_name] => Array
        (
            [required] => 0
            [default_value] => 
            [form_name] => txtStoredFileName
            [type] => text
            [message] => 
            [db_tablename] => pp_jobs
        )

    [type] => Array
        (
            [required] => 0
            [default_value] => 
            [form_name] => txtType
            [type] => text
            [message] => 
            [db_tablename] => pp_jobs
        )

)

Open in new window

So in my comment #a41828049 I said "Please make sure that your $fields[$key]['form_name'] does translate to the name of the textarea."
Were you really checking against another field which is not the textarea?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Updated code
foreach ($fields as $key => $value) {
	if (isset($_POST[$fields[$key]['form_name']]))
	{
		
		$temp = trim($_POST[$fields[$key]['form_name']]);  // Translates to eg. $temp = trim($_POST['txtBookTitle'])  

		if ($fields[$key]['required'] == 1)
		{
			$temp = isset($_POST[$fields[$key]['form_name']]) 
			   ? preg_match('/\w+/', $_POST[$fields[$key]['form_name']]) 
			   : false;
			
			if ($temp)  {
			   echo "Input is valid";
			}
			else {
			   echo "input is invalid";
			}
			exit();
		}

		/*if (empty($temp) && $fields[$key]['required'] == 1)
		{
			$error_array[] = $fields[$key]['message'];
			${$key} = '';
		}*/
	}
}

Open in new window

Use real_escape_string just before you enter the data into the database.
Move the escape_string to after the check for validity

That's it!

Many thanks all.
Thanks for your time and help everyone.  I should give the whole story next time, I was trying to simplify for convenience.
You are welcome.