简体   繁体   中英

How do I reject entries with invalid characters using preg_match and filter_var?

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.

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, [^az] 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM