Web Membership Profile - Error checking a serial number

I've implemented the website membership plugin on our site and it's working wonderfully. Shortly after launching I got a request from Marketing to enhance security by adding a serial number field with error checking.

Here's what I'm trying to do:
- Limit entry to 9 characters (and stripping out any extra spaces introduced by the form user)
- First two must be numbers (i.e. last two digits of a year "12" or "13" etc.)
- Third must be a letter (entered as either upper or lower case)
- The last six should be numbers

Based on this post:
http://www.interactivetools.com/iforum/Products_C2/CMS_Builder_F35/Field_Validation_P92584/gforum.cgi?post=85966

I've modified the code for my purposes as such:

/// Check Serial Number
function format_serial_number($serial){
//strip out spaces
$tmpSerial = str_replace(" ","",$serial);
$tmpSerial = str_split($tmpSerial);

if(@$tmpSerial[0]==1 && @$tmpSerial[1]==2|3|4|5 && @$tmpSerial[2]==a-z){ //number is in correct format. Return it as is.

$serial = implode($tmpSerial);
}
else{ //error. The number is in an invalid format.

return false;
}

return $serial;
}
//format serial number.
$serial = format_serial_number(@$_REQUEST['serial']);
if(!$serial){ $errorsAndAlerts .= "You must enter a valid serial number! <br/>\n";}


My questions:
- Will the '$tmpSerial[1]==2|3|4|5' work to display either 2, 3, 4 or 5?
- How do I tell it to allow a-z and A-Z?
- How would I keep the field limited to 9 total characters?

Haven't had a chance to test anything out yet - was hoping to have more coded but got stuck. Any help is appreciated!

Cricket7475

Re: [cricket7475] Web Membership Profile - Error checking a serial number

By Dave - October 10, 2012

Hi cricket7475,

This would probably be a good use for regular expressions:
http://webcheatsheet.com/php/regular_expressions.php

How about something like this:

// serial error checking
$_REQUEST['serial'] = preg_replace("/[^\da-z]/i", '', @$_REQUEST['serial']); // remove chars that aren't a digit or a letter
$isValidSerial = preg_match("/^\d\d[a-z]\d\d\d\d\d\d$/i", $_REQUEST['serial']); // valid format: 2 numbers, 1 letter, 6 numbers
if (!$_REQUEST['serial']) { $errorsAndAlerts .= "No serial number entered!<br/>\n"; }
elseif (!$isValidSerial) { $errorsAndAlerts .= "You must enter a valid serial number, example: 11A111111!<br/>\n"; }
elseif ($_REQUEST['serial'] == '11A111111') { $errorsAndAlerts .= "Please enter your actual serial number, not the example one!<br/>\n"; }


Let me know if that works for you.
Dave Edis - Senior Developer
interactivetools.com