Generate random string and validate unique

I am wanting to generate a string and make sure its unique against a database attribute.

I know how to generate the random string like so;

In model;

By adding this to the rules() of the model be a success?

So as you can see I'm not 100% sure how to validate randomString against database properly. Any advise would be great.

For me, adding 'unique' to the rules is working very well.

Just what you have done is sufficient, i think.

Very nice if I have seen this few hours a go. I needed the same a cooked something here that goes to my globals.

function gfRandKey($minlength=12, $maxlength=12, $useupper=true, $usespecial=false, $usenumbers=true)

{

    $charset = "abcdefghijklmnopqrstuvwxyz";

    if ($useupper) $charset .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    if ($usenumbers) $charset .= "0123456789";

    if ($usespecial) $charset .= "~@#$%^*()_±={}|][";

    for ($i=0; $i<$maxlength; $i++) $key .= $charset[(mt_rand(0,(strlen($charset)-1)))];

    return $key;

}