(NBC News) The Supreme Court has narrowly upheld a law designed to keep guns out of the hands of criminals and the mentally ill.

In a 5-4 decision, justices ruled that a gun buyer must disclose at the time of purchase if they plan to sell or transfer the weapon to someone else, even if that person can legally own a gun.

The ruling is a victory for gun control advocates who say the case had the potential to strike a gaping hole in the federal law preventing what’s known as straw purchases.

A former Virginia police officer had challenged the law after he got in trouble for falsely stating on this government form that he was the actual gun buyer, when in fact the gun was meant for his uncle.

The officer argued the law shouldn’t apply to him since his uncle could legally own the weapon.