0

I am trying to use preg_match and filter_var to check form entries. I created two functions that should return false when the fields contain invalid characters. For the Username, the invalid characters would be numbers and symbols. Whats wrong with my functions?

username function:

function verifyUsername($x){
    if (!preg_match('/[^a-z\s-]/i',$x)) {
        return 0;

    }
    else {
        return 1;
    }
}

email address function:

function verifyEmailAdd($x){
    if (!filter_var($emailadd, FILTER_VALIDATE_EMAIL)) {
        return 0;

    }
    else {
        return 1;
    }
}

I am calling them like:

goodemail = verifyEmailAdd($emailAdd);
gooduser = verifyUsername($userName);

They always return 1.

Beehive
  • 23
  • 1
  • 7

1 Answers1

0

In the verifyEmailAdd function, you have:

if (!filter_var($emailadd...

But in the function declaration you have $x, so $emailadd is undefined in this scope.

You would notice it, if you had error_reporting enabled - see https://stackoverflow.com/a/5438125/4568686

Second thing - in the verifyUsername function, I'm not sure what you meant by your regex, if you want to accept only alpha characters, [^a-z] should be enough.

Well, here you go with modifications:

<?php

function verifyUsername($x){
    if (preg_match('/[^a-z]/i',$x)) {
        return 0;
    }
    else {
        return 1;
    }
}

function verifyEmailAdd($x){
    if (!filter_var($x, FILTER_VALIDATE_EMAIL)) {
        return 0;

    }
    else {
        return 1;
    }
}

var_dump(verifyUsername("45wqadf"));
var_dump(verifyUsername("wqadf"));
var_dump(verifyEmailAdd("45wqadf@&%"));
var_dump(verifyEmailAdd("wqadf@blah.com"));

You can test it here: https://3v4l.org/kVDiK

konrados
  • 1,047
  • 8
  • 21