This is contract law. There is nothing in legal codes that stipulated that this is valid, but rather that by signing a document that allowed for a signatory to void the contract if one of the terms was broken (don't do drugs... don't do criminal acts) is a valid agreement and the contract documented it was signed, thus the clean roommate was allowed to void his agreement without penalty for the exit because of the terms within. You can call it a loophole or a clause but it's perfectly valid as the contract was entered without any duress by both parties and the terms were violated.
It should also be pointed out most shows in the vein of "Judge Judy" are not actually being handled in a real courtroom setting or real civil trial, but a set that is designed to look like a court room. What is actually going on is a legal process called "Binding Arbitration" where both parties in a disagreement sign a separate contract stating that they will agree to the decision of a neutral arbiter, who need not be a judge (though having a legal background is very helpful). With rare exception, the outcome cannot be appealed or elevated to a real civil court (unless the losing party is not cooperating with the arbiter's judgement, or the case is dismissed without prejudice, which is judge speak for allowing a civil case to be refiled or filed with another court. Typically this happens when the plaintiff is the victim of something that requires a little more legal authority in the judgement.).
They also don't typically do this in a real court room but in a conference room. The court room trappings in these tv shows are for the audience. Arbitration does not create a legal precedence and typically the requested settlement must be small claims ($5,000 or less) though Judge Judy type shows will pay for travel and lodging for both parties and their witnesses regardless of outcome.