Search code examples
phpregexvalidationalphanumeric

Validate that a string is wholly alphanumeric and has a qualifying length


I need to define a pattern so that the input string can only contain 0-9, a-z, and A-Z. Also, the length is in the range of 1-30.

Here is the script:

$fileBaseName = 'abc12345';

if (!preg_match("/^[a-zA-Z0-9]{1, 30}$/", $fileBaseName)) {
    echo '<br/>' . 'invalid' . '<br/>';
} else {
    echo '<br/>' . 'valid' . '<br/>';
}

However, when I run this code, the return always is 'invalid'.

How to fix this issue?


Solution

  • You need to drop the space:

    if (!preg_match("/^[a-zA-Z0-9]{1,30}$/", $fileBaseName)) {