Reputation: 1900
How can I make "email" field not mandatory? Even if someone is not filling the field, the form should submit.
In the below code, the "email" field is mandatory.
I tried to add if !isset
email field so that the $email_from
will get the word "empty", but it didn't work for me.
<?php
if(isset($_POST['name'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "[email protected]";
$email_subject = "Messeage from your site";
function died($error) {
?>
<?php
die();
}
// validation expected data exists
if(!isset($_POST['name']) ||
//!isset($_POST['email']) || /* i tried to comment this line, but didnt work. */
!isset($_POST['telephone']))
{
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
// create email headers
$headers = 'מאת: '.$email_from."\r\n".
'חזור ל: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>
<?php
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=thank_you.html">';
exit;
?>
<?php
}
?>
Upvotes: 0
Views: 1060
Reputation: 413
check if email is valid or not using FILTER_VALIDATE_EMAIL in php5
if(isset($_POST['email']))
{
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo $email." E-mail is not valid.";
}
else
{
echo $email." E-mail is valid.";
}
}
Upvotes: 0
Reputation: 308
The preg_match
on $email_form
makes it required.
If you first check if $email_form
is set, and than perform the preg_match
it must work.
Like this:
if(!empty($_POST['email'])){
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br/>';
}
} else {
$email_from = '';
}
Upvotes: 1
Reputation: 1900
I did , and it work:
if(!empty($_POST['email'])){
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
}
Upvotes: 0
Reputation: 286
if(!isset($_POST['name']) ||
!isset($_POST['telephone'])){
if(isset($_POST['email'])){
//all code for email inside here
}
}
this should do trick, while $_POST['email'] is empty it should´t bother you anymore.
Upvotes: 1