Validate and sanatize a user entered DEA Registration ID with PHP

Home   »   Validate and sanatize a user entered DEA Registration ID with PHP

    /**
     * Validate and clean a DEA Registration ID
     * @param string $enteredValue user supplied DEA ID 
     * @param string $lastname OPTIONAL extended validation requires first letter of users last name to match corresponding character in ID
     * 
     * @return string|bool returns sanitized alphanumeric DEA Registration ID or FALSE 
     */
    function cleanDEA(string $enteredValue, string $lastname = '') {
        
        //if a " Supervisee Identifier" was supplied, just ignore it 
        $parts = explode("-",$enteredValue);
        $deanumber = preg_replace( '/[\W]/', '', $parts[0]); // also strip anything that's not a letter or number  
        $dea = strtoupper($deanumber);
        //value should be 9 characters
        if(strlen($dea) != 9){
            return false;
        }

        //First character must be a letter, but not "I","O","Q","V","W","Y", or "Z"
        $cannotStartWith = ["I","O","Q","V","W","Y","Z"];
        if(in_array($dea[0],$cannotStartWith) || is_numeric($dea[0])){
            //exit('fail because '. $dea[0] .' is not the right letter');
            return false;
        }

        //Second character is a letter (from registrants last name) OR the number "9" if registered as a business
        if(is_numeric($dea[1]) && $dea[1] !== 9){
            return false;
        }
        elseif($lastname != '' && strtoupper($lastname[0]) !== $dea[1]){
            return false;
        }

        $last7 = substr($dea,-7);
        if(!is_numeric($last7)){
            return false;
        }
        $numberParts = str_split($last7);

        $odds = $numberParts[0] + $numberParts[2] + $numberParts[4]; // add the odd numbers
        $evens = ($numberParts[1] + $numberParts[3] + $numberParts[5]) * 2; // add the evens and double 
        $together = ($odds + $evens) % 10; //get last digit of the odds/evens combined
        return ($together == $numberParts[6]) ? $dea : false;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *