I wanted to validate the form in PHP but it doesn't give any output from validate.php
this PHP code didn't give any output after submitting the Form help me with this form validation
validate.php
function validate($data, $reg_exp = "") {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if (empty($data) == true) {
$Err = "EMT_FLD";
return false;
} else{
if ($reg_exp != "") {
if (preg_match($reg_exp, $data) !== true) {
$Err = "PRG_MTH_ERR";
return false;
} else {
return true ;
return $data;
}
}else {
return true ;
return $data;
}
}
}
register.php
include 'validate.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$fnErr = $lnErr = $unErr = $emErr = $psErr = $cpErr = "";
$submit = false;
if ($val = validate($_POST['firstname'],"/^['a-zA-Z']+$/")) {
if ($val == false) {
if($Err == "EMT_FLD"){
$fnErr = "<span class = 'error'>First Name Required</span>";
}
if($Err == "PRG_MTH_ERR") {
$fnErr = "<span class = 'error'>Invalid First Name, Only Letters Are Allowed (A-Z and a-z)</span>";
}
}elseif($val == true){
$firstname = $_POST['firstname'];
}
}
}
echo $fnErr."<br>";
Expected: It Should Return the $fnErr
, But It Returns Nothing
you have some problem in your logic.
return
stop the function execution. So your validate
function always return a boolean and not your error code. You should return the error string and check if it's empty or not.
I propose that :
validate.php
function validate($data, $reg_exp = "") {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if (empty($data) == true) {
return "EMT_FLD";
} else{
if ($reg_exp != "") {
if (preg_match($reg_exp, $data) !== true) {
return "PRG_MTH_ERR";
} else {
return '';
}
}else {
return '';
}
}
}
register.php
include 'validate.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$fnErr = $lnErr = $unErr = $emErr = $psErr = $cpErr = "";
$submit = false;
if ($val = validate($_POST['firstname'],"/^['a-zA-Z']+$/")) {
if ($val !== '') {
if($val == "EMT_FLD"){
$fnErr = "<span class = 'error'>First Name Required</span>";
}
if($val == "PRG_MTH_ERR") {
$fnErr = "<span class = 'error'>Invalid First Name, Only Letters Are Allowed (A-Z and a-z)</span>";
}
}elseif($val === ''){
$firstname = $_POST['firstname'];
}
}
}
echo $fnErr."<br>";