问题
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);
?>
回答1:
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
回答2:
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.
回答3:
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.
回答4:
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!
来源:https://stackoverflow.com/questions/24361078/making-email-field-required-in-php