Form validation server side in wordpress - php

I am new to wordpress. I have a custom contact form in frontend and i have to validate the data.
Will I have to make validation class or is there any hooks provided by wp.

Regardless of what you use WordPress for, there’s a range of common functions people need their site to perform that aren’t bundled with WordPress. This leaves you with two choices, installing a plugin or creating it yourself.
I am validating form data with my own class wrapper. following are some of the methods you can use :
function handleContactForm() {
if($this->isFormSubmitted() && $this->isNonceSet()) {
if($this->isFormValid()) {
$this->sendContactForm();
} else {
$this->displayContactForm();
}
} else {
$this->displayContactForm();
}
}
public function sendContactForm() {
}
function isNonceSet() {
if( isset( $_POST['nonce_field_for_submit_contact_form'] ) &&
wp_verify_nonce( $_POST['nonce_field_for_submit_contact_form'], 'submit_contact_form' ) ) return true;
else
return false;
}
function isFormValid() {
//Check all mandatory fields are present.
if ( trim( $_POST['contactname'] ) === '' ) {
$error = 'Please enter your name.';
$hasError = true;
} else if (!filter_var($_POST['contactemail'], FILTER_VALIDATE_EMAIL) ) {
$error = 'Please enter a valid email.';
$hasError = true;
} else if ( trim( $_POST['contactcontent'] ) === '' ) {
$error = 'Please enter the content.';
$hasError = true;
}
//Check if any error was detected in validation.
if($hasError == true) {
echo $error;
return false;
}
return true;
}
function isFormSubmitted() {
if( isset( $_POST['submitContactForm'] ) ) return true;
else return false;
}

if you try to use contact form 7 plugin, then you have validation plugin available for this,i.e Jquery Validation For Contact Form 7
or try
http://code-tricks.com/contact-form-7-custom-validation-in-wordpress/

Related

Gravity Forms regex for US ZIP code

I'm trying to set up some form validation for a Gravity Form that I've created. One of the fields that I need to validate is a US ZIP code. I want to pass ZIPs that follow the nnnnn and nnnnn-nnnn patterns. Here's my code:
if ( $field->type == 'address' ) {
$zip = rgar( $value, $field->id . '.5' );
if ( preg_match( "(^(?!0{5})(\d{5})(?!-?0{4})(|-\d{4})?$)", $zip ) && ! $field->get_input_property( '5', 'isHidden' )
) {
$result['is_valid'] = false;
$result['message'] = empty( $field->errorMessage ) ? __( 'Please enter a valid ZIP code (ie. 00000 or 00000-0000).', 'gravityforms' ) : $field->errorMessage;
} else {
$result['is_valid'] = true;
$result['message'] = '';
}
}
My form continues to fail validation and I can't figure out why. I've double checked that .5 is the correct input field number of the ZIP code. Any suggestions?
My form can be found at http://marcusjones.wpengine.com/
shouldn't be easier to use:
/(^\d{5}$)|(^\d{5}-\d{4}$)/
or other function fe:
function isValidPostalCode(postalCode, countryCode) {
switch (countryCode) {
case "US":
postalCodeRegex = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/;
break;
default:
postalCodeRegex = /^(?:[A-Z0-9]+([- ]?[A-Z0-9]+)*)?$/;
}
return postalCodeRegex.test(postalCode);
}
and "if" you'll add quite simple.

How can I allow only 2 dots after # in email validation php using ereg

I am trying to validate email in php using ereg, where I am not allowed to enter more than two dots after # and it can't begin with any special character, how can I do it.
function chk($a)
{
$pattern = "^([A-Za-z0-9\.|-|_]{1,60})([#])";
$pattern .="([A-Za-z0-9\.|-|_]{1,60})(\.)([A-Za-z]{2,3})$";
if (!#ereg($pattern, $a))
return false;
else
return true;
}
Please don't roll your own email validation.
if(filter_var($email, FILTER_VALIDATE_EMAIL) === true){
return true;
} else {
return false;
}
preg_match("/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/",'test#test.co.in.');
function custom_email_confirmation_validation_filter( $your_email ) {
if(!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $your_email )){
return 'invalid';
}
if( substr_count($your_email, '.') > 3){
return 'invalid 1';
}
return 'valid';
}
echo custom_email_confirmation_validation_filter('golapk.kkk.khazi#gmail.com');

PHP class method call not displaying all errors

<?php
class Validator {
public $errors = array(
'password' => '',
'email' => '');
const PASSWORD_MINCHARS = 8;
public function checkEmail($email) {
if ($this->checkEmpty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->errors['email'] = "Please provide a valid email";
return FALSE;
} else {
return TRUE;
}
} else {
$this->errors['email'] = "Please provide a value for the email";
return FALSE;
}
}
public function checkPassword($string) {
if ($this->checkEmpty($string)) {
if (strlen($string) < self::PASSWORD_MINCHARS) {
$this->errors['password'] = "The password should be atleast ".self::PASSWORD_MINCHARS." characters long.";
return FALSE;
} else {
return TRUE;
}
} else {
$this->errors['password'] = "Please provide a value for the password";
return FALSE;
}
}
private function checkEmpty($string) {
if (!empty($string)) {
return TRUE;
}
return FALSE;
}
public function displayErrors() {
$output = '';
foreach ($this->errors as $error) {
if (!empty($error)) {
$output .= '<p>'.$error.'</p>';
}
}
return $output;
}
}
?>
<?php
require 'Validator.php';
$validator = new Validator();
$email = '';
$password = '';
if ($validator->checkPassword($password) && $validator->checkEmail($email)) {
echo 'You have entered a valid password and email.';
} else {
echo $validator->displayErrors();
}
?>
The above code comes from two separate files. The one that comes begins with class Validator comes from Validator.php while the one that begins with the require function comes from index.php. So am just wondering why the method call that is $validator->displayErrors() in index.php only displays one error at a time instead of displaying them all at once.
There is only one error displayed because of your condition:
if ($validator->checkPassword($password) && $validator->checkEmail($email))
It executes your checkPassword method first, it returns false and so the second condition (which should execute the second validation method) is never checked.
You can avoid this by executing the validation methods first:
$validPassword = $validator->checkPassword($password);
$validEmail = $validator->checkEmail($email);
if ($validPassword && $validEmail) {
echo 'You have entered a valid password and email.';
} else {
echo $validator->displayErrors();
}
Replace
if ($validator->checkPassword($password) && $validator->checkEmail($email))
with
if ($validator->checkPassword($password) || $validator->checkEmail($email)) {

Header Redirect after form Validation in PHP

I am trying this code as part of form processing:
<?php
if(isset($_POST['senderEmail']))
{
try
{
require '_php/_security/validation.php'; //SEE BELOW
$rules = array(
'senderEmail' => 'validEmail',
'emailTextbox' => 'validTextbox',
);
$validation = new Validation();
if ($validation->validate($_POST, $rules) == TRUE) {
require("_php/database/dbProcessing.php"); //Form Proccessing for database inclusion
}
else {
foreach($validation->emailErrors as $error){
$emailErrors[] = $error;
$_SESSION['$emailErrors'] = $emailErrors;
header('Location:indexmobile.php#emailErrors');
die('ABORT!');
}
}
}
catch (PDOException $e)
{
$error = 'Error adding elements to database: ' . $e->getMessage();
echo "Error: " . $error;
exit();
}
exit();
}
?>
The validation.php where I do my validation has this:
<?php
class Validation {
public $errors = array();
public function validate($data, $rules) {
$valid = TRUE;
foreach ($rules as $fieldname => $rule) {
$callbacks = explode('|', $rule);
foreach ($callbacks as $callback) {
$value = isset($data[$fieldname]) ? $data[$fieldname] : NULL;
if ($this->$callback($value, $fieldname) == FALSE) $valid = FALSE;
}
}
return $valid;
}
public function validEmail($value, $fieldname) {
$valid = !empty($value);
if ($valid == FALSE) {
$this->emailErrors[] = "The $fieldname is required";
return $valid;
} else {
$valid = filter_var($value, FILTER_VALIDATE_EMAIL);
if ($valid == FALSE) $this->emailErrors[] = "The $fieldname needs to be a valid email";
return $valid;
}
}
public function validTextbox($value, $fieldname) {
$valid = !empty($value);
if ($valid == FALSE) {
$this->emailErrors[] = "The $fieldname is required";
return $valid;
} else {
$whitelist = '/^[a-zA-Z0-9 ,\.\+\\n;:!_\-#]+$/';
$textarea = strip_tags($value);
$textarea = mysql_real_escape_string($textarea);
$valid = preg_match($whitelist, $textarea);
if ($valid == FALSE) $this->errors[] = "The $fieldname contains invalid characters";
return $valid;
}
}
}
Upon using this, Im have issues with the redirect (I think). It seems further that Im having errors in validation. My questions are thus:
Am I doing the header redirect correctly? I've read that " header() must be called before any actual output is sent,.." So is this the reason why this redirect is incorrect? how to make a redirect if i need to show/send something to the redirected page?
function validTextbox always ends up an error that the field is empty. Why so?
Is my entire process of form validation a good way of validating form fields (which i learned from watching an online tutorial)? What is a better way?
Is there something wrong with error reporting in this case?
Thank you for those who replies. I am new to PHP and trying my best to learn the language.
1 - There are several ways to pass on a message to the page you are redirecting to. One is through $_GET like this
$message="Some message for the next page.";
$message=urlencode($message);
header("Location:page.php?message=".$message);
then on page.php
if(!empty($_GET['message']))
{
$_GET['message'];
}
similarly you can also use the session (less secure)
$_SESSION['message']='some other message';
then on page.php
if (!empty($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
2 - I would have to see what you are passing to your validate function. You should do a var_dump of $_POST and add that to your question.
3 - It depends on your criteria. If you are just checking for emptiness its overkill. I don't know what text you need / consider valid, but a regex is a reasonable way of enforcing validation.
4 - See #2.

PHP - Cleaner, More Elegant Way to Validate Content of Forms

I am currently working on a Upload page, where users enter in values to forms then click submit. I am going to check to see if the forms have been submitted, and if submitted that they weren't empty. Here is my current code
function validPost()
{
if(isset($_POST["title"]) && //if a post has been submitted
isset($_POST["artist"]) &&
isset($_POST["genre"]) &&
isset($_POST["url"]) &&
isset($_POST["user"]) )
{
if (strlen($_POST['title']) <= 0) {
echo 'ERROR: Please enter a title. </ br>';
return false;
}
else if (strlen($_POST['artist']) <= 0) {
echo 'ERROR: Please enter an artist. </ br>';
return false;
}
else if (strlen($_POST['genre']) <= 0) {
echo 'ERROR: Please select a genre. </ br>';
return false;
}
else if (strlen($_POST['url']) <= 0) {
echo 'ERROR: Please enter a url. </ br>';
return false;
}
else if (strlen($_POST['user']) <= 0) {
echo 'ERROR: Please enter a username to submit the song (or make one up). </ br>';
return false;
}
else
return true;
}
else //if no post was submitted
{
return false;
}
}
Is there a more elegant way to check this? I plan on adding more checks in the future to the content submitted by these forms and I feel like this is a sloppy way to do it.
Thanks!
Assuming that all of the fields will be check for non-zero string lengths only:
$field_checks = array(
// 'fieldname' => 'errormessage'
'title' => 'Please enter a title',
'url' => 'Please enter a URL',
etc...
);
$errors = array();
foreach ($field_checks as $field => $errmsg) {
if (!isset($_POST[$field]) || ($_POST[$field] === '')) {
$errors[] = $errmsg;
}
}
if (count($errors) > 0) {
print_r($errors); // probably want a nicer error display than this
return false;
}
Check into jQuery and the validate plugin

Categories