I am using jQuery Form Validation Plugin to do comprehensive client side validation.
Now I would like to use PHP to do the server side validation.
Check whether the email is email, age is in the right range, etc.
Is there similar package or function collections that I can use rather than write all validation method manually?
Thank you
If you're writing more or less complex application, you probably would benefit from using a framework, such as Zend Framework for instance. It has some standalone classes to aid validation process as well, for example Zend_Validate: http://framework.zend.com/manual/en/zend.validate.html
The closest thing that's bundled with PHP is the filter extension. It does validation and sanitization.
for email validation you can use is_email function.
Check the link:http://www.ohloh.net/p/isemail
These are a couple of methods I use
<?php
function chkReq($fields) {
foreach($fields as $name) {
if(req($name)) {
global $values;
$values[$name] = $_POST[$name];
} else {
global $errors;
$errors[$name] = "This field is required";
}
}
}
function req($name) {
if(isset($_POST[$name]) && !empty($_POST[$name])) {
return true;
} else {
return false;
}
}
function chkDate($name, $from, $to) {
global $errors;
global $values;
if(!req($name)) {
$errors[$name] = "This field is required";
} elseif(!betweenNumbers($_POST[$name], $from, $to)) {
$errors[$name] = "Value must be between $from en $to .";
$values[$name] = $_POST[$name];
} else {
$values[$name] = $_POST[$name];
}
}
function betweenNumbers($value, $from, $to) {
if($value >= $from && $value <= $to) {
return true;
} else {
return false;
}
}
function chk3Fields($field1, $field2, $field3) {
global $errors;
global $values;
if(!req($field1) && !req($field2) && !req($field3)) {
$errors[$field1] = "One of the three fields is required";
$errors[$field2] = "One of the three fields is required";
$errors[$field3] = "One of the three fields is required";
} else {
$values[$field1] = $_POST[$field1];
$values[$field2] = $_POST[$field2];
$values[$field3] = $_POST[$field3];
}
}
function checkRegistry($name){
global $errors;
global $values;
if(!req($name)) {
$errors[$name] = "This field is mandatory";
} elseif(!validRegistry($_POST[$name])) {
$errors[$name] = "This is not a valid registry number";
$values[$name] = $_POST[$name];
} else {
$values[$name] = $_POST[$name];
}
}
function validRegistry($value) {
$value = preg_replace("/(\.|-)/", "", $value);
$firstPart= substr($value, 0,9);
$residueFirstPart= $firstPart% 97;
$calculatedControlNr = 97 - $residueFirstPart;
$obzervedControlNr = substr($value, 9, 2);
return ($calculatedControlNr == $obzervedControlNr);
}
?>
Related
I have a form in which I am using a preg_match function to validate fields. I have a generalized function for the matching. The function validateForm() is being called earlier on in the script with the appropriate values.
When the function is NOT passed any values, all the fields show the error message despite having correctly matching information. Generalized function with no arguments:
function validateForm() {
if(preg_match()) {
return true;
}
else {
return false;
}
} // end function validateForm
When I pass just ONE specific regex/field pair argument, all the fields begin to validate and show the error message when appropriate (so basically the code works as it should despite having a field-specific argument in the function). For example, when I pass this single regex/field argument into preg_match, all the fields begin to validate each field correctly, regardless of the fact that I am only checking for the 'City' field in this case. Example of passing a field-specific argument, in which all the code 'works':
function validateForm($cityRegex, $city) {
if(preg_match($cityRegex, $city)) {
return true;
}
else {
return false;
}
} // end function validateForm
Can someone explain to me why, when passed a specific argument for a specific field, the function will work for all individual preg_match arguments in the code? The script is running as I would want it to, I just do not understand why the specific argument is what makes it validate all fields.
Here is all of the PHP code, if needed:
<?php
$first = '';
$last = '';
$phone = '';
$city = '';
$state = '';
$error_message = '';
$firstLastRegex = '/^[a-zA-Z]{2,15}$/';
$lastRegex = '/^[a-zA-Z]{2,15}$/';
$phoneRegex = '/^(\(\d{3}\))(\d{3}\-)(\d{4})$/';
$cityRegex = '/^[a-zA-Z]{3,20}$/';
$stateRegex = '/^[a-zA-Z]{2}$/';
$validate_first = '';
$validate_last = '';
$validate_phone = '';
$validate_city = '';
$validate_state = '';
$phone_string = '';
if(isset($_POST['submit'])) {
$first = $_POST['firstName'];
$last = $_POST['lastName'];
$phone = $_POST['phoneNumber'];
$city = $_POST['userCity'];
$state = $_POST['userState'];
$show_form = false;
$phone_string = str_replace(array('-', '(', ')'), '', $phone);
$validate_first = validateForm($firstLastRegex, $first);
$validate_last = validateForm($lastRegex, $last);
$validate_phone = validateForm($phoneRegex, $phone);
$validate_city = validateForm($cityRegex, $city);
$validate_state = validateForm($stateRegex, $state);
if($validate_first == false) {
$show_form = true;
$error_message .= "Please enter your FIRST name between 2 and 15 letters.<br>";
}
if($validate_last == false) {
$show_form = true;
$error_message .= "Please enter your LAST name between 2 and 15 letters.<br>";
}
if($validate_phone == false) {
$show_form = true;
$error_message .= "Please enter your phone number in (###)###-### format.<br>";
}
if($validate_city == false) {
$show_form = true;
$error_message .= "Please enter your city name between 3 and 20 letters.<br>";
}
if($validate_state == false) {
$show_form = true;
$error_message .= "Please enter your state's abbreviation (Example: CA).<br>";
}
} // end if isset();
else {
$show_form = true;
$error_message = "";
} // end else
// REGEX FUNCTION
function validateForm() {
if(preg_match()) {
return true;
}
else {
return false;
}
} // end function validateForm
?>
You still need to have arguments for you function. The code below will make your validate function work.
function validateForm($regEx, $field) {
if(preg_match($regEx, $field)) {
return true;
}
else {
return false;
}
} // end function validateForm
I also see other potential issues with not checking if post variables are set before using them, and you are setting $show_form = true for all your if/else cases. I'm sure you can figure everything else out with some debug statements.
<?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)) {
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.
I am new to PHP, so I apologize if this looks like a mess... I am trying to validate a form using the following three functions - checkName, checkEmail, and checkMessage. The problem I am running into is when I submit the form, it always displays the first error, even if the input is correct. Can anyone tell me what I'm doing wrong?
function checkName(){
if($name == ''){
print "Please enter your name!<br />";
return false;
}
else{
if(strlen($name)<2) {
print "Your name should be more than 1 characters long!<br />";
return false;
}
else{
return true;
}
}
}
function checkEmail(){
if($from == '') {
print "Please enter your email address!<br />";
return false;
}
else{
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $from)){
print "Please enter a valid email address!<br />";
return false;
}
else{
return true;
}
}
}
function checkMessage(){
if($message == '') {
print "Please enter your message!<br />";
return false;
}
else{
if(strlen($message)<10) {
print "Your message should be more than 10 characters long!<br />";
return false;
}
else{
return true;
}
}
}
if($validation == ''){
$a = checkName();
$b = checkEmail();
$c = checkMessage();
$result = array($a, $b, $c);
return $result;
Pass the variables to test into your functions to check them. The way you have it now, it would assume you are using global variables for $name,$message,$email. That would require the use of the global keyword (or some other options) in the functions, but is considered poor practice. Best to pass the variables
Called as:
$a = checkName($name);
$b = checkEmail($email);
$c = checkMessage($message);
Definitions
// Pass variable to function
function checkName($name){
if($name == ''){
print "Please enter your name!<br />";
return false;
}
else{
if(strlen($name)<2) {
print "Your name should be more than 1 characters long!<br />";
return false;
}
else{
return true;
}
}
}
function checkEmail($email){
// etc...
}
function checkMessage($message){
// etc...
}
By the way, as someone who frequently has to maintain old PHP code written by others, I can tell you that it is highly recommended that you do not use variable names like $a,$b,$c. Instead make them readable like $nameResult, $emailResult, $messgeResult.
In the functions your variables are not defined. If they are defined at all you have to use global $variable in your functions to have them defined in your functions
example:
bad:
$var = 'Hello';
function fun () {return $var;}
echo fun () . ' world';
good:
$var = 'Hello';
function fun () {
global $var;
return $var;
}
echo fun () . ' world';
I'm building a website that contains users with user profiles. Many of the fields in the profile are optional.
There is an opportunity for a lot of user-generated content, and so I need to display the author of this content in many different locations of the site (comments, posts, etc.). In the user's profile, he is able to (optionally) fill out his "first name", his "last name", and a "display name".
To display the author, I wrote a helper method that looks through a provided array of these fields and returns the most appropriate name for the user, in this order of preference:
If the user filled out display_name, this will be displayed.
If the user filled out first_name and last_name, but no display_name, it will display both names
If the user only filled out first_name, it will display first_name.
If the user only filled out last_name, it will display last_name.
If all else fails, a user id will be displayed i.e. user123
If none of the array keys are present, or the parameter is NULL, the name will display as NULL
The method works great, but it's ugly. There must be a way to beautify this with an alternative to nested if/else statements.
public function nameify($names = NULL) {
$name = '';
if (!empty($names)) {
if (!empty($names['display_name'])) {
$name = $names['display_name'];
} elseif (!empty($names['first_name'])) {
$name = $names['first_name'];
if (!empty($names['last_name'])) {
$name .= ' ' . $names['last_name'];
}
} elseif (!empty($names['last_name'])) {
$name = $names['last_name'];
}
if (empty($name) && !empty($names['id'])) {
$name = 'user' . $names['id'];
} else {
$name = 'NULL';
}
} else {
$name = 'NULL';
}
return $name;
}
public function nameify($names = NULL) {
if ($names) {
if (!empty($names['display_name'])) {
return $names['display_name'];
}
if (!empty($names['first_name'])) {
$name = $names['first_name'];
}
if (!empty($names['last_name'])) {
$name .= ' ' . $names['last_name'];
}
if (empty($name) && !empty($names['id'])) {
$name = 'user' . $names['id'];
}
}
return $name ? ltrim($name) : 'NULL';
}
Set the default first, and return that if nothing else matches. Then since we always want to return the display name if we have it do just that.
EDIT: Tweak to prevent returning "NULL "
Using ternary conditions we can shorten and beautify the code:
public function nameify($names = NULL) {
$name = 'NULL';
if (!empty($names)) {
$name = ($names['display_name']) ? $names['display_name'] : trim($names['first_name']." ".$names['last_name']);
if(!$name) $name = ($names['id'] > 0) ? 'user'.$names['id'] : 'NULL';
}
return $name;
}
I would propose this:
public function nameify($names = null) {
if(empty($names))
return null;
if(!empty($names['display_name']))
return $names['display_name'];
if(!empty($names['first_name'])) {
$name = $names['first_name'];
if (!empty($names['last_name'])) {
$name .= ' ' . $names['last_name'];
}
return $name;
}
if(!empty($names['id]))
return 'user' . $names['id'];
return null;
}
It is not much, but because $name it is at least NULL:
public function nameify($names = NULL) {
$name = 'NULL';
if (!empty($names)) {
if (!empty($names['display_name'])) {
$name = $names['display_name'];
} elseif (!empty($names['first_name'])) {
$name = $names['first_name'];
if (!empty($names['last_name'])) {
$name .= ' ' . $names['last_name'];
}
} elseif (!empty($names['last_name'])) {
$name = $names['last_name'];
}
if ($name=='NULL' && !empty($names['id'])) {
$name = 'user' . $names['id'];
}
}
return $name;
}
//pointers to functions
$arrayOfSulutions{"display_name_strategy", "full_name_strategy" ..., "null_strategy" }
function display_name_strategy{
return $names['display_name'];
}
$i = 0;
while($res == null){
$res = call($arrayOfSulutions[$i++]);
}
Somewhat less readable, but effective):
list($idx,$name) = array_shift(array_filter(array(
$names['display_name'],
implode(' ',array_filter(array($names['first_name'],$names['last_name']))),
'user'.$names['id'];
)));
A State machine works very nicely for involved logic like that. It's very simple to implement as well (using a switch statement).
I'm not sure that my version would be simplier, but here it is:
public function nameify($names = null) {
$result = array();
if( !empty($names['display_name']) ) {
array_push($result,$names['display_name']);
} else {
if( !empty($names['first_name']) ) {
array_push($result, $names['first_name']);
}
if( !empty($names['last_name']) ) {
array_push($result, $names['last_name']);
}
}
if( empty($result) && !empty($names['id']) ) {
array_push($result, 'user'.$names['id']);
}
return (empty($result) ? 'NULL' : implode(' ', $result));
}
I'd go with:
if( empty($names['display_name']) ) {
$name = $names['first_name'] . ' ' $names['last_name'];
else
$name = $names['display_name'];
$name = trim($name);
if( empty($name) )
$name = 'user'.$names['id'];
if( empty($name) )
$name = 'NULL';
This would be the 'core logic'... there will need to be other checks like $names != NULL or something..