I have a ContactForm7 form which submits data to a CRM. All works fine but now I need to differentiate between mobile and landline numbers. If a number starts with 07 it will be accepted as a mobile number.
looking at other threads I've tried the following but now neither the mobile or telephone field are being populated in the crm or being passed to the log file?
function process_contact_form_data( $contact_form ) {
$title = $contact_form->title;
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
$posted_data = $submission->get_posted_data();
}
if ( 'Quote Form_Contact' || 'Quote Form_Product' || 'Quote Form' == $title ) {
$firstName = $posted_data['user_first_name'];
$lastName = $posted_data['user_last_name'];
$email= $posted_data['your-email'];
$phone = $posted_data['your-number'];
$message = $posted_data['your-message'];
$bp = $posted_data['BP'][0];
$phone = $pattern;
$pattern = "/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/";
$match = preg_match($pattern,$phone);
if ($match != false) {$mobile = $phone;} else {$mobile= '';};
}
$error = false;
try
{
$relationshipId = postRelationship($firstName,$lastName,$email,$phone,$bp);
$opportunityId = postOpportunity($relationshipId,$message);
postOpportunityNote($relationshipId,$opportunityId,$message);
// postTask($relationshipId);
}
catch (Exception $e)
{
$error=true;
}
if($error || !isset($relationshipId) || !isset($opportunityId) || $relationshipId <= 0 || $opportunityId <= 0)
{
$log->lfile(ABSPATH . 'quotevine.log');
$log->lwrite('ERROR: With Email Address ' . $email);
$log->lclose();
}
}
add_action( 'wpcf7_before_send_mail', 'process_contact_form_data');
Your are overwriting your $phone variable in this line $phone = $pattern; with an undefined variable which will cause $phone to be NULL.
But after commenting out that line, the value of $mobile will still not be correct because a mobile number starts with 07 and the regex matches both the landline and the mobile number, for example:
07123123123
+447123123123
What you could do is if the match succeeded, check if the string starts with +44 to verify it is a mobile number.
preg_match returns false if an error occurred but I think you want to verify if the match is correct.
$phone = "+447123123123";
$pattern = "/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/";
$mobile= '';
if (preg_match($pattern,$phone) && 0 === strpos($phone, '07')) {
$mobile = $phone;
}
You overwrite the phone with an undefined variable.
// Phone is now a phone number I assume
$phone = $posted_data['your-number'];
$message = $posted_data['your-message'];
$bp = $posted_data['BP'][0];
// $pattern is as far as I can see undefined
// $phone =NULL
$phone = $pattern;
// You set pattern
$pattern = "/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/";
// Here you regex if the pattern matches NULL which it does not.
$match = preg_match($pattern,$phone);
Related
I am trying to validate a phone number using PHP, and would like to know if there's a way to do it with FILTER_SANITIZE_NUMBER_INT instead of regex.
I need the password to enforce the xxx-xxx-xxxx format (allows '-') and max length of 12 characters.
This is my code so far. Would this work to validate any number into the xxx-xxx-xxxx format?
$phone = clean_input($_POST["phone"]);
if (empty($phone)) {
$phoneErr = "Valid phone number required";
$isValid = false;
} else {
if (!filter_var($phone, FILTERSANITIZE_NUMBER_INT)) ;
$phone_to_check = str_replace("-", "", $filtered_phone_number);
if (strlen($phone_to_check) < 10 || strlen($phone_to_check) > 12) {
$isValid = false;
}
}
I would use preg_match instead as you can cover all your needs in one statement. This regex assures that the value must have 10 digits, with optional - after the third and sixth digits.
$phone = clean_input($_POST["phone"]);
$isValid = preg_match('/^\d{3}-?\d{3}-?\d{4}$/', $phone);
Demo on 3v4l.org
I prefer using preg_match() functions for this style of regex.
An example based on your pattern
$phone = '000-000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
For validating using FILTER_SANITIZE_NUMBER_INT() try code below
function validate_phone_number($phone)
{
$filtered_phone_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
if (strlen($filtered_phone_number) < 12) {
return false;
} else {
return true;
}
}
Now below is the usage of the function that we have just created:
$phone = "444-444-5555";
if (validate_phone_number($phone) == true) {
echo "Phone number is valid";
} else {
echo "Invalid phone number";
}
first of all I'm using latest WordPress and CF7 version. I want to include the minlength validation for the tel field before. I know the syntax minlength=""
can be used inside the CF7, but for unknown reason, it won't work. Only maxlength="" is ok.
I already contacted the plugin support, but seems like no further response. So, I search here and found some code and I edit it so that the field will return an error if user put less than 10 characters. I put the codes inside functions.php
function custom_phone_validation($result,$tag){
$type = $tag['type'];
$name = $tag['name'];
if($name == 'Subject'){
$phoneNumber = isset( $_POST['phonenumber'] ) ? trim( $_POST['phonenumber'] ) : '';
if($phoneNumber < "9"){
$result->invalidate( $tag, "phone number is less" );
}
}
return $result;
}
add_filter('wpcf7_validate_tel','custom_phone_validation', 10, 2);
add_filter('wpcf7_validate_tel*', 'custom_phone_validation', 10, 2);
The result now is, it always display the "phone number is less" even though I insert more than 9 characters. May I know what wrong and how to solve it?
as I've tested you must have your tel field [tel* phonenumber tel-503] where phonenumber is name of postfield you are posting, second issue in your code is $name=='Subject' as you are validating tel so $name will be phonenumber. So it will be like this:
function custom_phone_validation($result,$tag){
$type = $tag['type'];
$name = $tag['name'];
if($name == 'phonenumber'){
$phoneNumber = isset( $_POST['phonenumber'] ) ? trim( $_POST['phonenumber'] ) : '';
if(strlen($phoneNumber) < 9){
$result->invalidate( $tag, "phone number is less" );
}
}
return $result;
}
add_filter('wpcf7_validate_tel','custom_phone_validation', 10, 2);
add_filter('wpcf7_validate_tel*', 'custom_phone_validation', 10, 2);
Your $phoneNumber is a string. You will need to get the length of the string to compare with 9.
Your code will become:
function custom_phone_validation($result,$tag){
$type = $tag['type'];
$name = $tag['name'];
if($name == 'Subject'){
$phoneNumber = isset( $_POST['phonenumber'] ) ? trim( $_POST['phonenumber'] ) : '';
if(strlen($phoneNumber) < 9){//<=====check here
$result->invalidate( $tag, "phone number is less" );
}
}
return $result;
}
add_filter('wpcf7_validate_tel','custom_phone_validation', 10, 2);
add_filter('wpcf7_validate_tel*', 'custom_phone_validation', 10, 2);
I have a query that I am not too sure how I can make it work
I have a form where the end users can add multiple email fields using jquery and it places each text input into an array
I have created some code that verifies each array key and fills an array with a number for verification purposes
Here is the code for verifying the POST:
// Collect and verify attached email
if(isset($_POST["email"])){
// set var for collecting email and store as null
$emailfields ="";
// start verify loop
foreach($_POST["email"] as $key => $email)
{
// Filter var email to comfirm it is an email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false)
{
$emailcheckarray[] = 1;
} else {
$emailcheckarray[] = 0;
}
// Create a string for later
$emailfields .= $email .",";
}
// Verify Array contains value
if (!in_array('1', $emailcheckarray, true))
{
$emailverification = 1;
} else {
$emailverification = 0;
}
}
echo $emailfields;
echo $emailverification;
Now this works it fills the array $emailcheckarray with 1 1 1 1 1 if the emails are valid depending on how many inputs the user uses.
Is there a way that I can get the in_array to only work with all keys being the same as currently if one of the keys are 0 it still outputs $emailverification as 1 if the user enters 1 valid email and the rest invalid when I want it to be 0.
You can just omit the in_array if you set the verification to 0 during the loop when any of the checks fails. So start with a value of 1 as you have no failures yet:
$emailverification = 1; // added
// start verify loop
foreach($_POST["email"] as $key => $email)
{
// Filter var email to comfirm it is an email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false)
{
$emailcheckarray[] = 1;
} else {
$emailcheckarray[] = 0;
$emailverification = 0; // added
}
// Create a string for later
$emailfields .= $email .",";
}
... and then at the end of the loop you have the correct value.
You can use functions such as array_map and array_filter to get an array of all the valid emails.
if (isset($_POST['email'])) {
$sanitized_emails = array_map(function ($email) {
return filter_var($email, FILTER_SANITIZE_EMAIL);
}, $_POST['email']);
$valid_emails = array_filter($sanitized_emails, function($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
});
$emailfields = implode(',', $sanitized_emails);
}
Then you just have to compare the size of the two tabs.
$emailverification = 0;
if (count($emails) == count($valid_emails)) {
$emailverification = 1;
}
Check the affirmative for zero:
if (in_array('0', $emailcheckarray, true)) {
$emailverification = 0;
} else {
$emailverification = 1;
}
If you don't have any zeros, that means they're all ones.
The following code validates a new user password by asking them to confirm their password by entering it twice:
// search to see if is a vvalid file path
if (($val["type"] == "password") && !strstr($key , "_confirm")) {
$name = $val["name"] ? $val["name"] : $key ;
if ($input[$name] != $input[$name . "_confirm"]) {
//preparing the message
$fields["error"] = "Password and confirmation doesn't match.";
$fields["errors"][$name] = 1;
$fields["errors"][$name . "_confirm"] = 1;
$fields["values"] = $input;
}
}
I would like to include additional validation (i.e., password contains at least 1 number and 1 letter, special characters [!##$%], must be at least 8 characters in length.
What would be the proper code syntax to nest with the above code? THX
To add the validation, you need to find the Regex you like, e.g.
http://regexlib.com/Search.aspx?k=password&AspxAutoDetectCookieSupport=1
Then use that regex in your code (replace $regEx with your choice):
if (($val["type"] == "password") && !strstr($key , "_confirm")) {
$name = $val["name"] ? $val["name"] : $key ;
if ($input[$name] != $input[$name . "_confirm"]) {
//preparing the message
$fields["error"] = "Password and confirmation doesn't match.";
$fields["errors"][$name] = 1;
$fields["errors"][$name . "_confirm"] = 1;
$fields["values"] = $input;
}
if( !preg_match( $regEx, $input[$name] ) ) {
$fields["error"] = "Password must contain...";
$fields["errors"][$name] = 1;
$fields["values"] = $input;
}
}
For one-upper, one-lower, and one-digit w/ min 8 chars:
$regEx = '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/';
Add in some special-char requirements:
$regEx = '/^(?=.*[!##$%])(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/';
I'm getting the error in the title of this question. Help me find what's wrong in my contact form:
<?php
//Prefedined Variables
$to = "example#example.com";
$subject = "1";
if($_POST) {
// Collect POST data from form
$name = stripslashes($_POST['name']);
$email = stripslashes($_POST['email']);
$comment = stripslashes($_POST['comment']);
// Define email variables
$message = date('d/m/Y')."\n" . $name . " (" . $email . ") sent the following comment:\n" . $comment;
$headers = 'From: '.$email.'\r\n\'Reply-To: ' . $email . '\r\n\'X-Mailer: PHP/' . phpversion();
//Validate
$header_injections = preg_match("(\r|\n)(to:|from:|cc:|bcc:)", $comment);
if( ! empty($name) && ! empty($email) && ! empty($comment) && ! $header_injections ) {
if( mail($to, $subject, $message, $headers) ) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
?>
It seems the problem is here, but I don't understand whats wrong!
$header_injections = preg_match("(\r|\n)(to:|from:|cc:|bcc:)", $comment);
Try with:
$header_injections = preg_match("#(\r|\n)(to:|from:|cc:|bcc:)#", $comment);
You must provide a valid symbol at the begining and at the end of you regex, in this example is just #, but you can use / or whatever you want.
Take a look at this article: RegEx delimiters.
Try using this:
$header_injections = preg_match('/(\r|\n)(to:|from:|cc:|bcc:)/', $comment);
Also on your IF condition, you should check $header_injections this way:
if( ! empty($name) && ! empty($email) && ! empty($comment) && FALSE !== $header_injections ) {
As the preg_match can return value that can be casted to boolean and skip your validation.