I'm new to php. What I'm trying to do right now is do a email validation form using regular expression. When a user enter something silly to the text field and click submit. It will show the email is invalid. I'm using regular expression to test whether user enter the right format. Can anyone please guide me how to link the php regular expression with the form together ?
<form action= " " method = "post">
<p> Enter your email </p>
<input type ="text" name ="user_email"/>
<input type ="Submit" />
</form>
<?php
$email = " abc#gmail.com ";
$regex = "^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
if (preg_match ($regex, $email )){
echo $email . "is a valid email";
}else{
echo $email. " is an invalid email ";
}
?>
Change
$email = " abc#gmail.com ";
to
$email = $_POST['user_email'];
Then it'll take input from the form. Since you're POSTing data to the script all of the variables you've posted will end up in the superglobal $_POST.
You can link the $_POST request in several ways, for example:
$email = $_POST['user_email'];
Also, preg_match needs a beginning and ending delimiter to function properly:
$regex = "/^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/";
Result:
abc#gmail.com is an invalid email
Example:
http://ideone.com/igphq1
Related
I want to place a default email address in when a custom form field is left blank. I can't get the code right. I use email address in place of the real email address.
<?php if(get_field('cemail')) { ?>
<?php
$email = (get_field('cemail'));
if($email!=""){
echo 'email address' ;
}
?>
You can do this like;
<?php
$email = $_GET["email"];
if($email=="" || !filter_var($email, FILTER_VALIDATE_EMAIL) === false)
$email = "default_email#email.com";
echo $email;
?>
If you just want to substitute a default value when the email field is blank. You can do this:
$email = (isset($_GET['cemail'])) ? $_GET['cemail'] : "defaultemail#email.com";
Don't forget to make sure submitted values are valid email addresses and always clean your inputs if values will go into a database!
How can I display a default value if the field was empty?
I assume that your procedural method get_field() simply just returns the value of a global variable GET or POST parameter so...
This can be achieved in 1 line with something called a ternary expression, an example is displayed below.
<form action="/member.php" method="post">
<input name='cemail' value="<?php echo (!empty(get_field('cemail')) ? get_field('cemail') : 'default#me.com'; ?>" id="cemail">
</form>
We're firstly checking if the field is not empty (!) and then using that result inside the ternary expression to dictate what to do.
Here are some sources to help you understand further what's happening above:
Ternary Expressions
PHP Empty Syntax
Try this:
<?php if(get_field('cemail'))
{
$email = (get_field('cemail'));
if(trim($email) == "")
$email = 'default#email.com';
}
echo $email;
}
?>
I'd like to verify if an user entered something in an input tag :
here is the index.php page :
<form action="email_validation.php" method="post">
<p>
Enter email : <input type="text" name="email" id="email" /><br />
<input type="submit" value="Envoyer" />
</p>
</form>
and the email_validation.php :
if(isset($_POST['email']))
{
$req = $bdd->prepare('INSERT INTO newsletter(email) VALUES(:email)');
$req->execute(array(
'email' => $entree = $_POST['email']
));
echo 'Email added';
}
else
{
echo 'Enter something';
}
It seems that my condition with isset() function is not working... when I'm testing this, "Email added" is displayed even if I'm not writing anything and a blank value is added to the database . When someone write nothing, I want to display "Enter something" and don't execute the query. I searched for hours and can't resolve this... Thanks is advance !
You are not validating the input. You are just testing if the value exists. And it is, the _POST will have the email field, with an empty value. In order to validate it, the code should be:
if(!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$req....
} else {
echo "No valid email provided";
}
Hope that helps.
That's because isset will check if variable is set and is not null.
When you send your form without typing email $_POST['email'] will contain empty string so isset will return true.
You have to use empty for that (or check length) and also it's good idea to additionally check if email is in correct format.
This question already has answers here:
Making email field required in php [closed]
(4 answers)
Closed 8 years ago.
I have this existing code and I am wondering how to make the name and email field required?
<?php
if(isset($_POST['submit'])){
$to = "xxx#email.com"; // this is your Email address
$from = $_POST['gift_email']; // this is the sender's Email address
$first_name = $_POST['gift_name'];
$subject = "Free Gift Request";
$msg = "A free gift has been requested from the following:"."\n";
$msg .= "Name: ".$_POST["gift_name"]."\n";
$msg .= "E-Mail: ".$_POST["gift_email"];
$headers = "From:" . $from;
mail($to,$subject,$msg,$headers);
//echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
header('Location:free_program_thankyou.php');
}
?>
For form
<input type="text" name="gift_email" required>
<input type="text" name="gift_name" required>
For Php
if(empty($_POST['gift_email']))
{
echo 'This field is required';
}else {
//Do what you want to do here
}
A two basic ways to do this:-
Within the php program check each required form field has been filled in send a new page with an error message back if it is not. Be sure to return the contents of any fields already filled in or your users will wish a plague of boils on your person.
Validate in javascript. Have a function triggered by the "onsubmit" condition which checks for all required forms fields are filled and highlights any that are not. see here
In practice a robust web site will do both. This seems like duplication however the javascript function is much more responsive and user friendly, BUT, the php server side validation cannot be gamed by turning JS off or spoofing responses.
I am new to PHP so sorry if my question seems a bit noobish. I am creating a contact form which is working great but I need to validate two fields; the phone number and the email address, I need it to check that the phone number field has only numbers and is 11 digits long. The email field needs to be "something"#"something"."something".
If possible I would prefer to do it using only html or php (whichever is easiest), I guess that if there is a way to put the validation into the field properties, that would be the easiest way? eg: in here:
<input type="text" name="email" id="email" class="text" form="contact_form" required/>
If that is not possible then maybe in my PHP file which looks like so:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Submitting...</title>
</head>
<body>
<?php
$Name = $_POST ['full_name'];
$Email = $_POST['email'];
$Number = $_POST['phone_number'];
$Company = $_POST['company_name'];
$Message = $_POST['message'];
$formcontent="Name: $Name
\n Email: $Email
\n Number: $Number
\n Company: $Company
\n Message: $Message";
$recipient = "info#vicarage-support.com";
$subject = "Contact";
$mailheader = "From: $Email \r\n";
ini_set("sendmail_from","info#vicarage-support.com");
mail($recipient, $subject, $formcontent, $mailheader) or die("Please try again.");
echo("Form Submitted.");
?>
<script type="text/JavaScript">
<!--
setTimeout("location.href = 'http://www.vicarage-support.com/contact_us.html';",3000);
-->
</script>
</body>
</html>
Thank you in advance.
There are two ways to check form data before submission, i.e. client-side: using JavaScript, and using new (HTML5) HTML attributes for the input element. They can be used together if desired. Neither of them guarantees valid data; client-side checking should be regarded as convenience to the user, not as a way of ensuring data validity (which you need to check server-side, in this case in PHP code).
The HTML way can be exemplified this way:
<input type="email" name="email" id="email" class="text" form="contact_form"
required>
<input type="tel" name="tel" id="tel" class="text" form="contact_form"
required pattern="\d{11}" label="11 digits">
Using type="email" means that conforming browsers will check the email address format. This is a nontrivial task. Using type="tel" does not impose format restrictions (and the format varies by country and authority), but it may make browsers use a better user interface (such as a numeric keypad in touchscreen devices). The restriction is imposed by the pattern attribute. The value \d{11} means exactly 11 digits. (This is bad usability. I think you should allow spaces, and possibly parentheses and other characters as well, and strip them on the server. It is just too difficult to input an 11-digit number without any grouping. And 11 digits sounds arbitrary.)
There are several approaches to implementing the same in JavaScript. The pattern check is simple, whereas email format checks are very tough, and there are different library routines for it. In general, the check should be fairly permissive, basically just checking that there is an “#” character.
If you want to validate this form before it is submitted, that will have to be done with javascript. However, you should still check in your server side code, as javascript could be disabled, which would render javascript validation useless.
I've used this in the past, worked well for my needs.
http://validval.frebsite.nl/
Try adding three variables. First add a $pattern variable, then add two variables and use the switch function.
Sort of like...
<?php
$what = what you are checking (phone, email, etc)
$data = the string you want to check
function isValid( $what, $data ) {
switch( $what ) {
case 'Number':
$pattern = "/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i";
break;
//Change to a valid pattern, or configure it the way you want.
case 'Email':
$pattern = "/^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/i";
break;
default:
return false;
break;
This shows you what you want. Now try to validate it like...
}
return preg_match($pattern, $data) ? true : false;
}
$errors = array();
if( isset($_POST['btn_submit']) ) {
if( !isValid( 'phone', $_POST['Number'] ) ) {
$errors[] = 'Please enter a valid phone number';
}
if( !isValid( 'email', $_POST['Email'] ) ) {
$errors[] = 'Please enter a valid email address';
}
}
if( !empty($errors) ) {
foreach( $errors as $e ) echo "$e <br />";
}
?>
As you can see, this will validate your form. You may have to configure it so the $pattern is set ti what you want it to be. This may not be the best way to do so, and I reccomend Javascript, but this is how you could do it with PHP and HTML.
I hope I'm missing something pretty basic here but: An empty form is getting submitted randomly, sometimes 3-8 times a day, then none for a few days and so on.
The empty submits always email with the subject as "[Website Contact Form]." Even though there is no validation in my php, in the html code the subject is chosen from a drop-down menu with the default as "General Enquiry." Notice in the php code below, there is no way for a human to submit an empty form with the above subject line, that is, it would always be "[Website Contact Form]General Enquiry" if I press submit without entering anything.
I have contact.html call this contact.php file:
<?
$email = 'info#mail.com';
$mailadd = $_POST['email'];
$headers = 'From: ' . $_POST['email'] . "\r\n";
$name = $_POST['name'];
$subject = '[Website Contact Form] ' . $_POST['subject'];
$message = 'Message sent from: ' . $name . '. Email: ' . $mailadd . '. Organization: ' . $_POST['company'] . '. Phone: ' . $_POST['phone'] . '. ';
$message .= 'Message: ';
$message .= $_POST['message'];
if (mail($email,$subject,$message, $headers)) {
echo "<p>Thank You! We'll get back to you shortly.</p>";
}
else {
echo "<p>Error...</p>";
}
?>
I use this code for many websites, but have never encountered this issue. Is there something so obviously wrong with this code that I'm missing? Any help would be greatly appreciated!
I suspect that you may not be checking that these variables are set before you send the email. Someone requesting contact.php directly (without any form data) may produce the results you have described. If this is the case, the following code should work like a charm:
<?php
if (isset($_POST['submit']) {
// form code
}
else {
// The form was not submitted, do nothing
}
?>
Even if that's not that case, such a simple check is always good practice.
Furthermore, you should always validate any user input just as a good habit. You don't want your server flooding your inbox with emails. I suggest using regexs to validate the input provided and possibly use a captcha service (such as ReCaptcha).
If you've been using this code and it's been working fine then I'd check what variables you changed with this case for example your submit form.
Try out your form with all common possibilities and see if it works. And empty Subject will give your form the subject "[Website Contact Form]". Check that your script actually get's the post variables and your form submits the right variables. Your dropdown might have an option with value of "" and the innerHTML "General Enquiry". The value is what will get submitted.
It's good to check inputs server-side as well
<?php
if(isset($_POST['subject'],$_POST['email'])){
}
?>