Making email field required in php [closed]

2019-03-07 17:47发布

I have a php script for the capture of a name and email address for a mailing list. If possible could someone please offer some adivce on how to make the email and name fields as required, so user is forced to input their name and email into form fields.

Again much appreciated for any help !!

The following is the php code being used for the form

<?php
$sendTo = "info@mail.com";
$subject = "website email enquiry";

$headers = "From: " . $_POST["firstName"] ." ". $_POST["lastname"] . "<" . $_POST["email"] .">\r\n";
$headers .= "Reply-To: " . $_POST["email"] . "\r\n";
$headers .= "Return-path: " . $_POST["email"];
$message = $_POST["message"];
mail($sendTo, $subject, $message, $headers);
?>

4条回答
2楼-- · 2019-03-07 18:25
if(filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
    //Your code
} else {
    //Show your errors
}

The above code will validate the contents of your e-mail post variable to be a valid email address.

查看更多
Evening l夕情丶
3楼-- · 2019-03-07 18:26

You have to check values of $_POST['firstname'], $_POST['lastname'] and $_POST['email']

For the the name, you can check it with :

empty()

if ( empty($_POST['firstname']) || empty($_POST['lastname']) )
  // catch error

You can also, use strlen() and trim() to check string size and not validate a name with only 1 character length.

For email, you can check it with :

filter validate

if ( !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
  // catch error
查看更多
虎瘦雄心在
4楼-- · 2019-03-07 18:31

You don't have to do this in PHP anymore. In your form where you have your email filed/textbox, just insert required and type as email then the form won't submit unless this fill contains a valid email address.

<input type="email" name="email" id="email" required value="<? echo $email; ?>" placeholder="example@fordberg.com"/>

That should do the trick. HTML5 Baby!

查看更多
Lonely孤独者°
5楼-- · 2019-03-07 18:37

Here's the best way to do this in PHP.

<?php
if(isset($_POST["email"])){
//Perform action
}
else{
echo "Please type in your email";
}
?>`

This should do the trick.

查看更多
登录 后发表回答