It's possible (though I haven't done any research) that the law may require a uniformed officer to make the stop and the hat is part of the uniform. No hat -> not uniformed -> not a legal stop.
Yes, that's the only explanation which would make any sense -- but it seems like a rather extraordinary combination of legislators and judge would be required to (a) write the law that way and (b) interpret a law so literally as to throw out a ticket over a missing hat.