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';
Related
This is a sample of individual functions that validate form data from a request submission. A variable of true has been set and each function checks for validation requirements then either continues without returning anything or returns false and changes the $check value. The function down the bottom then checks if the $check value has changed to false and if it has the SQL statement will not be run.
$check = true;
function productNameValidation(){
if(isset($_REQUEST['product_name']) && !empty($_REQUEST['product_name']) && preg_match("/^[A-Za-z0-9 :]*[A-Za-z0-9][A-Za-z0-9 :]{0,50}$/",($_REQUEST['product_name']))){
//then $valid['ID'] = "string: " . $_REQUEST['ID']
$valid['product_name'] = $_REQUEST['product_name'];
$err['product_name'] = "No errors";
//if not
} else {
if(empty($_REQUEST['product_name'])){
$valid['product_name'] = "No data entered!";
} else {
$valid['product_name'] = $_REQUEST['product_name'];
} //$err['ID'] = "error message"
$err['product_name'] = "Product Name must only contain letters, numbers and ':'!";
$check = false;
}
}
function checkProduct()
{
productNameValidation();
productGenreValidation();
productPriceValidation();
productEsrbValidation();
productThumbnailValidation();
releaseDateValidation();
return $check;
}
if($check == true)
{
//Insert into database
}
What you need to do is add different variables on different functions. If you are working this code to the method that it begins as true and is required to be checked and if the check fails then becomes false, try this method:
// $check = true;
function productNameValidation(){
$nameValidation = TRUE;
if(isset($_REQUEST['product_name']) && !empty($_REQUEST['product_name']) && preg_match("/^[A-Za-z0-9 :]*[A-Za-z0-9][A-Za-z0-9 :]{0,50}$/",($_REQUEST['product_name']))){
//then $valid['ID'] = "string: " . $_REQUEST['ID']
$valid['product_name'] = $_REQUEST['product_name'];
$err['product_name'] = "No errors";
//if not
} else {
if(empty($_REQUEST['product_name'])){
$valid['product_name'] = "No data entered!";
} else {
$valid['product_name'] = $_REQUEST['product_name'];
} //$err['ID'] = "error message"
$err['product_name'] = "Product Name must only contain letters, numbers and ':'!";
$nameValidation = false;
}
return $nameValidation;
}
function checkProduct()
{
$checkProduct = true; ///true until proven false.
$checkProduct = productNameValidation();
//This code gives $checkProduct the boolean value returned
//from the function
$checkProduct = productGenreValidation();
$checkProduct = productPriceValidation();
$checkProduct = productEsrbValidation();
$checkProduct = productThumbnailValidation();
$checkProduct = releaseDateValidation();
return $checkProduct;
}
if($checkProduct == true)
{
//Insert into database
}
What I have done here is each function returns a TRue/False flag boolean variables which can be checked with an if(){ statement, you can run through numerous functions in this way checking each aspect you need. The important point is that you need to return a value from each function and you can set the booleans manually with initial settings which is then updated upon conditionals - such as setting $checkProduct = TRUE until it is FALSE from any sub function.
Global variables are really not a good idea in this case.
Edit: Thanks to #Edward for some clarification of boolean return code.
You can do something like that:
function productNameValidation(){
$check = true;
if(isset($_REQUEST['product_name']) && !empty($_REQUEST['product_name']) && preg_match("/^[A-Za-z0-9 :]*[A-Za-z0-9][A-Za-z0-9 :]{0,50}$/",($_REQUEST['product_name']))){
//then $valid['ID'] = "string: " . $_REQUEST['ID']
$valid['product_name'] = $_REQUEST['product_name'];
$err['product_name'] = "No errors";
//if not
} else {
if(empty($_REQUEST['product_name'])){
$valid['product_name'] = "No data entered!";
} else {
$valid['product_name'] = $_REQUEST['product_name'];
} //$err['ID'] = "error message"
$err['product_name'] = "Product Name must only contain letters, numbers and ':'!";
$check = false;
}
return $check;
}
if(productNameValidation()) {
....
}
You can return $check in your validation functions which will allow you to use the value of $check outside the function scope like this: $check = productNameValidation(). Another important note which I saw mentioned above: You should try to avoid the global scope as much as possible.
You can use check like a local variable not global, so in function.
Instead if you want it as a global, at the beginning of the function, you have to specify that you referring to
global $check;
How can I echo the value returned from a function, called within another function in PHP.
For example, if I have function like this:
function doSomething($var) {
$var2 = "someVariable";
doSomethingElse($var2);
}
function doSomethingElse($var2) {
// do anotherSomething
if($anotherSomething) {
echo "the function ran";
return true;
}
else {
echo "there was an error";
return false;
}
}
I want to echo the echo from the second function inside the first. The reason is because the second function can produce a string when it fails that the first cannot.
So how would I output the returned value from the second function?
Create an array containing values that you would like to return and then return that array.
function doSomethingElse($var2) {
// do anotherSomething
if($anotherSomething) {
$response['message'] = "the function ran";
$response['success'] = TRUE;
}
else {
$response['message'] = "there was an error";
$response['success'] = FALSE;
}
return $response;
}
In your other function
$result = doSomethingElse($var2);
echo $result['message'];`
<?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)) {
im not sure on how i am going to explain this correctly.
I wanted a function to validate a string which i figured correctly.
But i want the function to return a boolean value.
And outside a function i need to make a condition that if the function returned false, or true that will do something. Here's my code.
i am not sure if this is correct.
<?php
$string1 = 'hi';
function validatestring($myString, $str2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
}
}
else {
return false;
}
}
if(validatestring == FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
EDIT : Now what if there are more than 1 condition inside the function?
<?php
$string1 = 'hi';
function validatestring($myString, $myString2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
return true;
}
else {
retun false;
}
}
else {
return false;
}
}
if(validatestring($myString, $myString2) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Functions need brackets and parameter. You dont have any of them.
This would be correct:
if(validatestring($myString) === false) {
//put some codes here
}
An easier and more elegant method would be this:
if(!validatestring($myString)) {
//put some codes here
}
<?php
$string1 = 'hi';
function validatestring($myString) {
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring($string1) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Sidenote, since empty() already returns false ,you could simplify by doing:
function validateString($string){
return !empty($string);
}
if(validateString($myString){
// ok
}
else {
// not ok
}
To make a check and test later:
$check = validateString($myString);
if($check){ }
There's no need to check == false or === false, the function already returns a boolean, it would be redundant.
store $string1 to $myString in the function
myString=string1
<?php
$string1 = 'hi';
function validatestring($myString) {
myString=string1;
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring() === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
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);
}
?>