I'm having a trouble getting my php script to validate user input what am I doing wrong here? This just displays the error message all the time.

for example:

if(!preg_match("/[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\ ]+$/",$name)||empty($name))
{
               print '<td colspan="2" class="ErrorText"><div align="right">Please enter a valid name without special characters i.e. *,/,&lt; etc. </div></td>';
							$error++;
}

Dani AI

Generated

Quick diagnosis: the condition in 's snippet combines a negated character class that is only anchored at the end with a logical NOT (!preg_match(...)). That makes the test true for most valid names, so the error branch runs every time. Also, escaping non-ASCII characters like is unnecessary and, without the /u (UTF-8) modifier, PCRE may not handle accented characters as you expect.

Two safe ways to fix this:

  • Positive-match the whole string (allow only the characters you want). Use Unicode-aware classes so accented letters are accepted:

    if (empty(trim($name)) || !preg_match('/^[\p{L}\p{N} .-]+$/u', $name)) {
        // invalid name
    }
  • Or detect any invalid character (simpler to reason about): if any character outside the allowed set exists, treat it as an error:

    if (preg_match('/[^\p{L}\p{N} .-]/u', $name) || trim($name) === '') {
        // invalid name
    }

Notes tied to the thread: 's eregi approach worked in older PHP but eregi is deprecated/removed—prefer preg_match (see the manual). 's ctype_alnum is fast and safe for ASCII-only usernames but will reject accented letters and spaces; use a Unicode-aware regex when international names must be allowed.

Additional tips: always trim() before validating, check length limits, use htmlspecialchars() when echoing user-supplied names to avoid XSS, and consider testing preg_match results with === 1 if you need to distinguish "no match" from a regex error. See the PHP docs for preg_match and ctype_alnum for details:
preg_match documentation
ctype_alnum documentation
eregi (deprecated)

Recommended Answers

All 2 Replies

I don't use preg_match, but this code works for me to make sure users only use numbers and letters.

if (eregi ("^[[:alnum:]]+$", $_POST['username'])) {
		$a = TRUE;
	} else {
		$a = FALSE;
		$message[] = "Please enter a username that consists only of letters and numbers.";
	
	}

You can also use ctype_alnum, this way:

$username = ctype_alnum($_POST['username']) ? $_POST['username'] : NULL;

if($username == NULL) {
  echo 'error message';
} else {
  echo $username;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.