/    Sign up×
Community /Pin to ProfileBookmark

Email validation on submit

I have a form on my home page for people to subscribe to a mailing list, this works and the content of my email address field gets stored correctly within my sqlsrv database.

Now I am trying to add email validation so have copied a bit of code from my registration script but this doesn’t work and still allows me to just submit “test”.

The code is as follows:

I have added this function just under the database connection details:

[CODE]function isEmail($email){
return preg_match(‘/^S+@[wd.-]{2,}.[w]{2,6}$/iU’, $email) ? TRUE : FALSE;
}[/CODE]

I have then added the following in the process of what happens when submit is clicked:

[CODE]// Validate Email
if(!isEmail($data[’emailAD’])) {
$err[] = “ERROR – Invalid email address.”;
//header(“Location: index.php?msg=$err”);
//exit();
}[/CODE]

And finally, just under my subscribe box on the home page I have inserted the following to display the errors:

[CODE]<?php
if(!empty($err)) {
echo “<div class=”msg”>”;
foreach ($err as $e) {
echo “* $e <br>”;
}
echo “</div>”;
}
?>[/CODE]

Thanks

to post a comment
PHP

20 Comments(s)

Copy linkTweet thisAlerts:
@tobias_wagnerApr 17.2012 — The problem is definitively not in the parts of code you provided. Everything is correct there. The function isEmail is probably called in the wrong place or time. You should provide more code to locate the problem
Copy linkTweet thisAlerts:
@djadejonesauthorApr 17.2012 — OK, my input within index.php is:

[CODE]<input type="text" name="emailAD">[/CODE]

on submit, the action is within emailsubscribe.php and the full content of this file is:

[CODE]<?php

include("sqlsrvdbc.php");

$emailAD=$_POST['emailAD'];

include ("connection.php");

// Validate Email
if(!isEmail($data['emailAD'])) {
$err[] = "ERROR - Invalid email address.";
//header("Location: index.php?msg=$err");
//exit();
}

header("Location: subscribed.php");

$query="INSERT INTO enquiries (EmailAddress, DateTimeEntered) VALUES ('$emailAD',GetDate())";

$result=sqlsrv_query($conn, $query);

if (!$result) {
echo $result;
die("Query failed");

} else {

echo "Success";
}

sqlsrv_free_stmt( $result);

sqlsrv_close($conn);;

?>[/CODE]


and the sqlsrvdbc.php include contains:

[CODE]<?php

$server="#"; // set database host
$username="#"; // set database user
$password="#"; // set database password
$database="#"; // set database name

function isEmail($emailAD){
return preg_match('/^S+@[wd.-]{2,}.[w]{2,6}$/iU', $emailAD) ? TRUE : FALSE;
}

?>[/CODE]


Thanks
Copy linkTweet thisAlerts:
@tobias_wagnerApr 17.2012 — Ok, this line is clear, you just create a variable $emailAD which stores the email from the input
[code=php]$emailAD=$_POST['emailAD'];[/code]

And here you validate the email. Where is that array [B]$data[/B] taken from? If it's full code of the file then that array may simply not exist
[code=php]if(!isEmail($data['emailAD'])) {[/code]

And if you actually created a variable which stores the email, why don't you use it like this?
[code=php]if(!isEmail($emailAD)) {[/code]
Copy linkTweet thisAlerts:
@djadejonesauthorApr 17.2012 — [CODE]$emailAD=$_POST['emailAD'];[/CODE] was just for the benefit of [CODE]$query="INSERT INTO enquiries (EmailAddress, DateTimeEntered) VALUES ('$emailAD',GetDate())";[/CODE]

but yes I agree that I could change [CODE]if(!isEmail($data['emailAD'])) {[/CODE] to [CODE]if(!isEmail($emailAD)) {[/CODE]

And i'm not too sure what the $data is from, I just copied this bit of code from my registration page, not sure if it has anything to do with the following which I just found within an include from the registration page, not sure what this is doing though:

[CODE]function filter($data) {
$data = trim(htmlentities(strip_tags($data)));

if (get_magic_quotes_gpc())
$data = stripslashes($data);

$data = mysql_real_escape_string($data);

return $data;
}[/CODE]
Copy linkTweet thisAlerts:
@tobias_wagnerApr 17.2012 — try this code and tell me the output you get

[code=php]<?php

include("sqlsrvdbc.php");

$emailAD=$_POST['emailAD'];

include ("connection.php");

echo '<pre>';
print_r($data);
echo '</pre>';

// Validate Email
if(!isEmail($emailAD) {
$err[] = "ERROR - Invalid email address.";
echo 'Email ' . $emailAD . ' is wrong';
}else{
echo 'Email ' . $emailAD . ' is correct';
}

//header("Location: subscribed.php");
exit('<br />stop point');

$query="INSERT INTO enquiries (EmailAddress, DateTimeEntered) VALUES ('$emailAD',GetDate())";

$result=sqlsrv_query($conn, $query);

if (!$result) {
echo $result;
die("Query failed");

} else {

echo "Success";
}

sqlsrv_free_stmt( $result);

sqlsrv_close($conn);;

?>[/code]
Copy linkTweet thisAlerts:
@djadejonesauthorApr 17.2012 — I had to add an extra ) within this line: [CODE]if(!isEmail($emailAD) {
[/CODE]

but after that and on submitting, I get:

Notice: Undefined variable: data in C:HostingSpacesJoPoTajopota.passingbuys.co.ukwwwrootemailsubscribe.php on line 10

Email ade test 2 is wrong

stop point
Copy linkTweet thisAlerts:
@tobias_wagnerApr 17.2012 — In your original code replace
[code=php]if(!isEmail($data['emailAD'])) {
[/code]
with
[code=php]if(!isEmail($emailAD)) {[/code]

It should work fine then
Copy linkTweet thisAlerts:
@djadejonesauthorApr 17.2012 — Have tried this but I still just keep getting redirected to the subscribed page with the content getting put in the database, and im only typing "test".
Copy linkTweet thisAlerts:
@tobias_wagnerApr 17.2012 — and did you uncomment these lines of code?
[code=php]//header("Location: index.php?msg=$err");
//exit();[/code]
Copy linkTweet thisAlerts:
@djadejonesauthorApr 17.2012 — Right, done that and it works (i think) because if I type in what looks like an email address, I go through to the subscribed page, and if I do test, it looks like its refreshing my index page but the error message doesnt display?
Copy linkTweet thisAlerts:
@tobias_wagnerApr 17.2012 — Well, that would be a second question ? Basically you assign an error message to an array $err[] but then you redirect to another page - and that means all the variables, arrays etc are lost

You need to find a way to pass the value (error message) to another page, either by using $_GET and passing it via URL, or using sesions, which is a bit more complicated
Copy linkTweet thisAlerts:
@djadejonesauthorApr 17.2012 — So would it be easier to just have a prompt pop up when the user clicks submit to say "your email address is not valid" and then the user has to click OK and correct their email, and if so, how is this done?

The code I have taken from my registration script to use for this works there so there must be a way, when someone fills out the registration page it uses the same validation stuff and if the email is not right, returns the registration page with a message under the input sayin "email is not valid", this is near enough to same script but doesnt display the message.
Copy linkTweet thisAlerts:
@djadejonesauthorApr 17.2012 — I have just removed the [] from [CODE]$err[] = "ERROR - Invalid email address.";
[/CODE]
and submitted the black field which then refreshed the index page and I noticed the error message was displaying in the address bar as this:

http://www.mydomain.co.uk/index.php?msg=ERROR&#37;20-%20Invalid%20email%20address.

How can I now get this to display where I have put:

[CODE]<?php
if(!empty($err)) {
echo "<div class="msg">";
foreach ($err as $e) {
echo "* $e <br>";
}
echo "</div>";
}
?>[/CODE]
Copy linkTweet thisAlerts:
@tobias_wagnerApr 17.2012 — Like this

[code=php]echo $_GET['msg'];[/code]
Copy linkTweet thisAlerts:
@criterion9Apr 17.2012 — Use SESSIONs.

[code=php]
$_SESSION['errMsg'][] = "Invalid Email Address"; //add array of messages to the session
[/code]

[code=php]
if(isset($_SESSION['errMsg']) && is_array($_SESSION['errMsg'])) {
echo "<div class="msg">";
foreach ($_SESSION['errMsg'] as $e) {
echo "* $e <br>";
}
echo "</div>";
unset($_SESSION['errMsg']); //clear the variable from session

}
[/code]


One thing to keep in mind is that each page will need a "session_start();" at the top in order for this to work.
Copy linkTweet thisAlerts:
@djadejonesauthorApr 17.2012 — Like this

[code=php]echo $_GET['msg'];[/code][/QUOTE]


Sorry for my lack of knowledge on this but where exactly do I put that? Just where I want the message to appear? And delete the rest of the code I had in there?
Copy linkTweet thisAlerts:
@tobias_wagnerApr 17.2012 — [code=php]$err = $_GET['msg'];[/code]

You would also need to remove [B]foreach [/B]loop, as it can be used for an array only. And as you changed it from [B]array $err[][/B] to [B]variable $err[/B] use simple echo command

[code=php]if(!empty($err)) {
echo "<div class="msg">";
echo "* $err <br>";
echo "</div>";
}
[/code]
Copy linkTweet thisAlerts:
@djadejonesauthorApr 17.2012 — OK so I have put [CODE]<?php
if(!empty($err)) {
echo "<div class="msg">";
echo "* $err <br>";
echo "</div>";

}
?>[/CODE]
where I want the error to appear but still unsure where your $err = $_GET['msg']; or echo $_GET['msg']; goes
Copy linkTweet thisAlerts:
@tobias_wagnerApr 17.2012 — You can place it anywhere before that piece of code, like this

[code=php]
$err = $_GET['msg'];

if(!empty($err)) {
echo "<div class="msg">";
echo "* $err <br>";
echo "</div>";

}
[/code]


or do it like this

[code=php]
if(!empty($_GET['msg'])) {
echo "<div class="msg">";
echo "* " . $_GET['msg'] . " <br>";
echo "</div>";

}
[/code]
Copy linkTweet thisAlerts:
@djadejonesauthorApr 17.2012 — Brill, thank you for all your help, youve been excellent!
×

Success!

Help @djadejones 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 6.14,
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: @meenaratha,
tipped: article
amount: 1000 SATS,

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

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