-2

I need to validate that the albumID input is 2 uppercase letters and 3 numbers. I used http://regexr.com/ and also http://www.tutorialspoint.com/php/php_preg_match.htm to confirm that this

preg_match('/([A-Z]{2}[0-9]{3})/', $albumid)

should work, but it's not:

        <?php
         // define variables and set to empty values
          $albumidErr =  $albumid = "";
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
           if (preg_match('/([A-Z]{2}[0-9]{3})/', $albumid))
            {
            $albumid = test_input($_POST["albumid"]);
            $albumidErr = print $albumid;
            }
           else { 
            $albumidErr = " Album ID must be 2 Uppercase letters and 3 numbers (i.e. BI010)";
            }

         }
        ?>
      <form method="post" action="
       <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
        <p>
            <label for="albumid">*Album ID:</label>
            <?php echo $albumidErr;?><br>
            <input type="text" name="albumid" id="albumid"/>
        </p>

        <p>
            <input type="submit" name="submit" id="submit" value="submit"/>
        </p>
    </form>
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • it won't work because its not correct – rock321987 Apr 24 '16 at 18:12
  • Possible duplicate of [Need regular expression for checking at least 3 uppercase, 3 lowercase, 3 digits and 3 special character](http://stackoverflow.com/questions/16689167/need-regular-expression-for-checking-at-least-3-uppercase-3-lowercase-3-digits) – rock321987 Apr 24 '16 at 18:13
  • 1
    If you provide exact specifications/requirements, and describe how your regex does not and should work. In your code, you provide an example `BI010`, but it is matched with `[A-Z]{2}[0-9]{3}`. Do you want to match it as an *entire string* (full string match)? See [**PHP preg_match full string**](http://stackoverflow.com/questions/16375856/php-preg-match-full-string). – Wiktor Stribiżew Apr 24 '16 at 18:18
  • Why the php question is tagged for `perl`? – clt60 Apr 24 '16 at 21:34
  • @jm666, The "p"` in "`preg_match`" stands for PCRE, which most people confuse for Perl. Fixed the tags. – ikegami Apr 25 '16 at 01:19

1 Answers1

0

In your code:

$albumidErr =  $albumid = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (preg_match('/([A-Z]{2}[0-9]{3})/', $albumid))

you're making $albumid empty then you're trying to match the regex with this empty string, of course, it doesn't match.

I guess you want:

$albumidErr =  $albumid = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (preg_match('/([A-Z]{2}[0-9]{3})/', $_POST["albumid"]))
    //                                     ^^^^^^^^^^^^^^^^^

and you can add anchors:

$albumidErr =  $albumid = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (preg_match('/^([A-Z]{2}[0-9]{3})$/', $_POST["albumid"]))
Toto
  • 89,455
  • 62
  • 89
  • 125