/    Sign up×
Community /Pin to ProfileBookmark

Form Validation – Help please

Hi guys. Could somebody please help.

I am very new to PHP and have been using a script to send a form to email. The form is working fine but I now need to add in required fields for some of the input areas. I currently have it working if the email address is not filled in correctly but would appreciate if someone could help me out with the other fields.

Here is the PHP I’m using:

[code=php]<?php
$email_to = “[email protected]”;
$name = $_POST[“name”];
$company_name = $_POST[“company_name”];
$address = $_POST[“address”];
$post_code = $_POST[“post_code”];
$tel_no = $_POST[“tel_no”];
$service = $_POST[“service”];
$additional = $_POST[“additional”];

$email = htmlspecialchars($_POST[’email’]);
if (!preg_match(“/([w-]+@[w-]+.[w-]+)/”, $email))
{
show_error(“E-mail address not valid”);
}

$email_from = “[email protected]”;
$message = $_POST[“message”];
$email_subject = “Website Enquiry”;
$headers =
“From: $email_from .n”;
“Reply-To: $email_from .n”;
$message = “Name: “. $name . “rnCompany Name: ” . $company_name . “rnAddress: ” . $address . “rnPost Code: ” . $post_code . “rnEmail: ” . $email . “rnService Required: ” . $service . “rnAdditional: ” . $additional;
ini_set(“sendmail_from”, $email_from);
$sent = mail($email_to, $email_subject, $message, $headers, “-f” .$email_from);
if ($sent)
{
header(“Location: thankyou.html”);
} else {
echo “There has been an error sending your comments. Please try later.”;
}

function check_input($data, $problem=”)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{

?>
[/code]

The error is currently returned like so:

[code=php]<?php echo $myError; ?>[/code]

Any help with this would be much appreciated.

Many thanks.

Jim

to post a comment
PHP

6 Comments(s)

Copy linkTweet thisAlerts:
@SrWebDeveloperNov 25.2009 — You're vague as to what "required" means, i.e. is the field missing entirely from the POST data, or is it simply blank. I wrote some code (tested, works) that checks for both and uses your error function as well.

In the example code below you'd edit $required_fields to list all the required field names that come from your form. At the top I create test post data, notice field2 is blank (to test blank fields) and $_POST['field4'] is intentionally missing (to test missing fields).

[code=php]

// Next 3 lines are test data -- for this example script only, remove the next 3 lines in your final version!

$_POST['field1']='hello';
$_POST['field2']='';
$_POST['field3']='blah';

// Set comma separated list of all required fields...
$required_fields="field1,field2,field4";

// Create an array from that list...
$required_arr=explode(",",$required_fields);

// Check if the form field is missing entirely or if value is blank and send error to your error function...
foreach ($_POST as $key => $value) {
if (!in_array($key,$required_arr)) {
show_error("The required field '$key' is missing.");
}
if (in_array($key,$required_arr) && empty($value)) {
show_error("The required field '$key' is blank.");
}
}
[/code]


This example doesn't break after the first error, it displays all errors with a line break prefix. Use PHP's "break" command after each show_error function call if you want it to stop after the first error.

You integrate the above (without the test data) into your code as you see fit, i.e. modify your check_input function, make a new function, or simply insert the code just before where you check for a valid email. This code is "proof of concept" intended to show you how in PHP you might accomplish your request - it's up to you to customize and tweak.

-jim
Copy linkTweet thisAlerts:
@strawberry-jimauthorNov 26.2009 — Thanks for this. Still struggling a little however so please excuse me if this is obvious but really not very experienced.

I have included the code you very kindly supplied and inserted the required fields as needed. The form is now showing an error with every field now though, not just the ones I've marked as required... if that makes sense...?

Here is my code anyway, if you can help any further that would be much appreciated.

[code=php]<?php
$email_to = "[email protected]";
$name = $_POST["name"];
$company_name = $_POST["company_name"];
$address = $_POST["address"];
$post_code = $_POST["post_code"];
$tel_no = $_POST["tel_no"];
$service = $_POST["service"];
$additional = $_POST["additional"];

$required_fields="name,post_code,tel_no,service";

// Create an array from that list...
$required_arr=explode(",",$required_fields);

// Check if the form field is missing entirely or if value is blank and send error to your error function...
foreach ($_POST as $key => $value) {
if (!in_array($key,$required_arr)) {
show_error("The required field '$key' is missing.");
}
if (in_array($key,$required_arr) && empty($value)) {
show_error("The required field '$key' is blank.");
}
}

$email = htmlspecialchars($_POST['email']);
if (!preg_match("/([w-]+@[w-]+.[w-]+)/", $email))
{
show_error("E-mail address not valid");
}


$email_from = "[email protected]";
$message = $_POST["message"];
$email_subject = "Website Enquiry";
$headers =
"From: $email_from .n";
"Reply-To: $email_from .n";
$message = "Name: ". $name . "rnCompany Name: " . $company_name . "rnAddress: " . $address . "rnPost Code: " . $post_code . "rnEmail: " . $email . "rnService Required: " . $service . "rnAdditional: " . $additional;
ini_set("sendmail_from", $email_from);
$sent = mail($email_to, $email_subject, $message, $headers, "-f" .$email_from);
if ($sent)
{
header("thankyou.html");
} else {
echo "There has been an error sending your comments. Please try later.";
}

function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{


?>[/code]


Thanks again,

Jim
Copy linkTweet thisAlerts:
@SrWebDeveloperNov 26.2009 — I explained it was proof of concept (mostly to show you the PHP commands) and to customize - not just copy/paste and edit one variable.

Look at my code, what it does is loop through the POST array and determine if the current key name is not found or value is missing in the required fields array of key names. What you need to do is reverse the logic, loop through the required fields array instead and compare with the POST array. Using my code, all it takes to do this is move the array names around in the source, simple as that. Something you can figure out on your own now that you know the PHP commands and what they do. If not, take a moment and visit php.net to learn more about each function.

Don't take this the wrong way, I'm not trying to be nasty or patronizing in any way, but when we offer advice here we don't normally code the entire solution and sometimes we miss the logic you want the first time. The latter happened here, unintentionally. We hope you honestly learn what you're doing, understand it, so you can figure these things out too!

-jim
Copy linkTweet thisAlerts:
@strawberry-jimauthorNov 27.2009 — Thanks for this Jim. All help has been much appreciated and I apologise if I took advantage of the forum in such a way.

It has highlighted a clear fact that I really need to learn more.

From a little further research I have come up with the following solution for now which seems to work:

[code=php]
if (empty($name))
{
show_error("Please fill in your name - hit back in the browser to correct");
}

if (empty($post_code))
{
show_error("Please fill in your name - hit back in the browser to correct");
}

if (empty($tel_no))
{
show_error("Please fill in your name - hit back in the browser to correct");
}

if (empty($service))
{
show_error("Please choose the service you require - hit back in the browser to correct");
}

$email = htmlspecialchars($_POST['email']);
if (!preg_match("/([w-]+@[w-]+.[w-]+)/", $email))
{
show_error("E-mail address not valid");
}[/code]


Many will probably be able to tell me there are a number of simplified ways of writing this and I will hopefully learn them soon enough but for now this seems to work.

Thanks again for your help pointing me in the right direction.

Gratefully.

Jim
Copy linkTweet thisAlerts:
@SrWebDeveloperNov 27.2009 — Don't forget to change the error messages for each condition. ?

If you wish to delve a little deeper into development, when I look at those conditions you created I see a function would economize the code, and maybe pass two arguments to it, i.e. pass current field from the POST array and a simple description:

[code=php]function CheckField($field='',$description) {

if (empty($field)) {
show_error("Please fill in the '$description' field - hit back in the browser to correct");
}

}[/code]


And you could even integrate the code we discussed before into the same function if you wished. This is a simple example to show you a concept of programming, to get you in that frame of mind - to think like a developer. The rest, syntax, learning functions, comes with trial and error and time. Job well done, so far, btw.

Okay, you're on your own from here, take your time and have fun - cheers.

-jim
Copy linkTweet thisAlerts:
@strawberry-jimauthorNov 27.2009 — Many thanks, all much appreciated.

Is all a fairly steep learning curve but getting there gradually I think.

Best regards,

Jim
×

Success!

Help @strawberry-jim spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...