Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form validation in php error in validate() function

Tags:

php

In this code, I cannot match the regular expressions in validate() function help me where I was wrong

I entered data in the user input other than alphabets like (john1246@##$##@+-) it returns the input value (john1246@##$##@+-) or $data in validate() function but not showing the error which should return PRG_MTH_ERR. what is the problem in my code?

validate.php

function validate($data, $reg_exp = "") {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if (empty($data) == true) {
        return "EMT_FLD";
    } elseif ($data != preg_match($reg_exp,$data)) {
        return "PRG_MTH_ERR";
    } else {
        return $data;
     }
}

login.php

if (isset($_POST['login'])) {
     include "./database/db.php";
     $db = new db();
     include 'validate.php';

     echo validate($_POST['user'],"/^['a-zA-z']$/");
}

I expected that it returns PRG_MTH_ERR but it returns $data

like image 851
samad Avatar asked Apr 13 '26 05:04

samad


1 Answers

Loose comparison is your issue :

elseif ($data != preg_match($reg_exp,$data)) {

Because "john1246@##$##@+-" == 0 is true.

You might compare 1 to the result of preg_match (see the doc to learn more about preg_match)

like image 171
Chocorean Avatar answered Apr 15 '26 20:04

Chocorean