Validating MongoId _id with PHP

November 17th 2012

In PHP, validation is essential for everything you do. I've needed to know recently whether a given string is a valid MongoId toString() representation of a Mongo ID.

I'm a avid user of Validation classes to ease the workload for future projects. Here's how I go about validating MongoIds.

PHP Code:
<?php
class Validate_MongoId {

    private 
$id;

    
/**
     * Initiate the class giving an expected MongoId.
     *
     * @param string $id
     */
    
public function __construct($id)
    {
        
$this->id $id;
    }

    
/**
     * Validate the given ID from the __construct
     *
     * @return boolean true for valid / false for invalid.
     */
    
public function isValid()
    {
        
$regex '/^[0-9a-z]{24}$/';
        if (
class_exists("MongoId"))
        {
            
$tmp = new MongoId($this->id);
            if (
$tmp->{'$id'} == $this->id)
            {
                return 
true;
            }
            return 
false;
        }

        if (
preg_match($regex$this->id))
        {
            return 
true;
        }
        return 
false;
    }

}

Now, here's how to use it:

PHP Code:
<?php
$toTest 
"506758e1b74ed04e24000001";
$validator = new Validate_MongoId($toTest);
if (
$validator->isValid()) {
    
// MongoId appears to be valid.
    
echo "Ok";
}
else {
    
// MonogId is invalid.
    
echo "Not Ok";
}

You'll notice that within the isValid() method, I use 1 of 2 available methods.

The best way possible to validate a MongoId is to use the native MongoId class to create an object with the given ID and then check the resulting _id->{'$id'} object to verify that the output is the same as the given id string.

If the user (or server) doesn't have the MongoId class ready, then the validator falls back to a simple 24 hexidecimal check regex.

I hope this helps someone out there!

Levani commented on Jul 11th 2013

MongoId throws an exception if the value provided isn't a valid mongoId string, so I would use 'try catch' block and return false if an exception is thrown.

Roger Thomas commented on Aug 6th 2013

Right you are. Although, this is apparently a newer behaviour. It used to return a different MongoId if the value given wasn't valid.

Paje commented on Oct 21st 2013

What about overriding __construct and rdeifene protected variable $_messageTemplate?class App_Validators_EmailValidator extends Zend_Validate_EmailAddress { public function __construct($options = array()) { parent::__construct($options); $this->_messageTemplates = array( self::INVALID => "My Custom 1", self::INVALID_FORMAT => "My Custom 2", self::INVALID_HOSTNAME => "My Custom 3", self::INVALID_MX_RECORD => "My Custom 4", self::INVALID_SEGMENT => "My Custom 5", self::DOT_ATOM => "My Custom 6", self::QUOTED_STRING => "My Custom 7", self::INVALID_LOCAL_PART => "My Custom 8", self::LENGTH_EXCEEDED => "My Custom 9", ); }}

matey commented on Feb 11th 2014

$regex = '/^[a-f0-9]{24}$/';