I'm building a website using PHP and I need to validate whether the name entered by the user is correct or not. Since JavaScript is client-side, I cannot completely rely on that, so here's my server-side function to validate the name of the user:
function validate_name($name) {
$name = trim($name); // only for the purpose of debugging <---- edited comment
echo $name;
if (strlen($name) <= 1) {
return "small";
} else if (has_numbers($name)) {
return "numbers";
} else {
return true;
}
}
After this, I check the input and display result accordingly:
function final_check() {
if (validate_name($_POST["first_name"]) == "small") {
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if (validate_name($_POST["first_name"]) == "numbers") {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
return true;
}
When I enter nothing in the first_name field, I get the empty error message; when I enter numbers, I get the numbers error message. However, when I do enter a valid name, it gives me the name empty error message.
Here's the post data:
Array
(
[email] => ewf#gmail.com
[first_name] => qwe
[last_name] => wqe
[password] => qwe
[re_password] => qwe
[gender] => Male
)
Output:
Your first name cannot be empty
Any idea what I am doing wrong? I have been stumped for the past hour trying to fix this and I haven't been able to find a solution.
Array
(
[email] => ewf#gmail.com
[first_name] => qwe
[last_name] => wqe
[password] => qwe
[re_password] => qwe
[gender] => Male
)
// First_name length = 3
function validate_name($name) {
$name = trim($name);
echo $name;
if (strlen($name) <= 1) {
return "small";
} else if (has_numbers($name)) {
return "numbers";
} else {
return true; // satisfy this case return true
}
}
and here it's becoming like
function final_check() {
if (validate_name($_POST["first_name"]) == "small") { // if(1 == 'small')
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if (validate_name($_POST["first_name"]) == "numbers") {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
return true;
}
if(1 == 'small') its a string comparison with Boolean which always going to return true.
Please check this page in the manual to understand the problem.
Your logic is correct, however, as other questions pointed out, string with boolean comparison will return true.
To fix this, you should use === instead of == and all should be fine
What I suggest here is to modify your validate_name function, so that it will have only one return type, since it can currently return either a string or a boolean, which is not a good practice.
For instance you can do something like :
function validate_name($name) {
$name = trim($name);
echo $name;
if (strlen($name) <= 1) {
return "small";
} else if (has_numbers($name)) {
return "numbers";
} else {
return "ok"; // or return ""; or whatever string you want.
}
}
Moreover to optimize your code and improve readability, you can change your final_check function so that there will be only one call to validate_name using a intermediate variabe.
function final_check() {
$valid = validate_name($_POST["first_name"]);
if ($valid == "small") {
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if ($valid == "numbers") {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
return true;
}
try with
if (validate_name($_POST["first_name"]) == "small" && !validate_name($_POST["first_name"])) {
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if (validate_name($_POST["first_name"]) == "numbers" && validate_name($_POST["first_name"])) {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
true == 'small' will also return true
or try with === will strictly match the values
if (validate_name($_POST["first_name"]) === "small") {
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if (validate_name($_POST["first_name"]) === "numbers"=) {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
I think you have to change only final_check() function
function final_check() {
if(validate_name($_POST["first_name"])){
return true;
}else{
if (validate_name($_POST["first_name"]) == "small") {
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if (validate_name($_POST["first_name"]) == "numbers") {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
}
}
Related
<?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 have a code like this
First looping count how many post the array:
for($i = 0; $i < $jumlah_qty ;$i++) {
if(!empty($qty[$i]) && !empty($id_cat[$i])) {
Insert booking:
$insert_booking_hd = $user_class->select($az);
$id_cates = $id_cat[$i];
for($b = 0;$b<$qty[$i];$b++) {
First validation if $_POST[$id_cates) is set run this code:
if(isset($_POST[$id_cates."".$b])){
$id_seat = $_POST[$id_cates."".$b];
Find the seat number in $select_seat and find if seat number is exist in $seat_number:
$select_seat = $user_class->select($query);
$seat_number = $user_class->select($querys);
$row_seat = $user_class->numrows($select_seat);
$row_seat2 = $user_class->numrows($seat_number);
if($row_seat>0) {
$update_seat = $user_class->update($update_false);
$bol[$b] = FALSE;
} else {
if( $row_seat2>0 ) {
$insert_booking_dt = $user_class->insert($insert);
$update_seat = $user_class->update($update_true);
$bol[$b] = TRUE;
} else {
$bol[$b] = FALSE;
}
}
} else {
$insert_booking_dt = $user_class->insert($insert_without_seat);
$bol[$b] = TRUE;
}
if($bol[$b]) {
echo "FALSE";
header("location:../../../print.php?id=$id_booking");
}
else {
echo "WRONG";
header("location:../../../event.php?msg=Same seat number");
}
}
}
}
Anything wrong with my php validation?
Because if I input array of $id_seat it will always redirect to print.php although validation is FALSE
for example if I input 3 array and then I echo FALSE WRONG FALSE FALSE
still redirect to print.php not to event.php
How can I read if one of array is get WRONG and then redirect to event.php?
How can I read if one of array is get WRONG and then redirect to event.php?
You may break out of for-loops.
Instead of:
else {
echo "WRONG";
header("location:../../../event.php?msg=Same seat number");
}
You could try:
else {
echo "WRONG";
header("location:../../../event.php?msg=Same seat number");
break 2;
}
I am usign jason_encode in php_ajax file, but I am having error message in consol, "Ajax error: 200 parsererror", Can You please review my code ??
I have one index file that show the status message on runtime using ajax and jason, this is my ajax file that send the true and false to my index with error message if exist otherwise it show the ok message if each check goes good.
$validateValue=$_REQUEST['fieldValue'];
$validateId=$_REQUEST['fieldId'];
$emailaddress = $validateValue;
$validateError= "email is not correct";
$validateSuccess= "email is correct";
$arrayToJs = array(); // creating array
$arrayToJs[0] = $validateId;
$arrayToJs[1] = $validateId;
if($numrow > 0) // where $numrow is getting data from database.
//if($validateValue !=="raza#gmail.com") // this check can also be used
{ // validate??
for($x=0;$x<1000000;$x++){
if($x == 990000){
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
//return false;
}
}
}
else
{
$arrayToJs[1] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
## Check for the ggg mail
}
if($validateValue == "ggg#gmail.com")
//check the second check
{ // validate??
for($x=0;$x<1000000;$x++){
if($x == 990000){
$arrayToJs[2] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
//return false;
}
}
}
else
{
$arrayToJs[2] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
}
Please Try This
$validateValue=$_REQUEST['fieldValue'];
$validateId=$_REQUEST['fieldId'];
$emailaddress = $validateValue;
$validateError= "deze naam wordt geblokkeerd";
$validateSuccess= "valid name";
/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
## check email Already Exist
if($numrow > 0 ) // this should return your value from database
//if($validateValue !=="raza#gmail.com")
{ // validate??
for($x=0;$x<50;$x++){
if($x == 9){
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
return false;
}
}
}
### Second Step
/// if you will use elseif instead of sigle if else statement it will work because it get only one message in array in a single time.
elseif($validateValue == "ggg#gmail.com")
{ // validate??
for($x=0;$x<1000000;$x++){
if($x == 990000){
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
return false;
}
}
}
else
{
$arrayToJs[1] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
}
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';