3

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

4 Answers 4

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

And btw, Igor is right, you have a mistake in your regex
2

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

In your code,

$data 

is never returned by

preg_match($reg_exp,$data)

Comments

2

Change

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

to

1 != preg_match($reg_exp,$data)

and regexp to /^[a-zA-Z]*$/

Comments

2

The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.

So just use }elseif (preg_match($reg_exp,$data)) { instead of }elseif ($data != preg_match($reg_exp,$data)) {

Hope it will help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.