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
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
$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