The U.S. District Court of the Northern District of California made the ruling Monday evening. Judge William Orrick III of San Francisco noted in his decision that the president and U.S. Attorney General Jeff Sessions have called the executive order "a weapon" to use against jurisdictions that "disagree with his policies of immigration."
"I concluded that the County of Santa Clara and the City and County of San Francisco had pre-enforcement standing to protect hundreds of millions of dollars of federal grants from the unconstitutionally broad sweep of the Executive Order," the judge wrote in his final decision on Monday.
Orrick originally issued a nationwide injunction against the order in April, but the Trump administration lodged an appeal. The final ruling said Trump had committed various constitutional violations, including taking control over Congress' spending powers.
Trump's order threatened funding for "sanctuary cities" in the United States, such as Los Angeles, San Francisco and New York City -- cities that have written or unwritten policies against cooperating with retainer orders from U.S. Immigration and Customs Enforcement on civil or public safety grounds.
"The Constitution vests the spending power in Congress, not the president, so the executive order cannot constitutionally placed new conditions on federal funds," Orrick said.
"The president does not have the power to place conditions on federal funds that Congress has not already imposed."
Orrick also said in the ruling that federal funding that has "no meaningful relationship to immigration enforcement cannot be threatened merely because a jurisdiction chooses and immigration enforcement strategy of which the president disapproves."
The injunction Monday won't have any immediate effect because the Trump administration hasn't tried to enforce the order.
There are hundreds of "sanctuary cities" in the United States, including some of the nation's largest metropolitan areas. Their general reasoning for refusing to comply with deportation orders involves various concerns they say would arise if they cooperated.
U.S. Department of Justice spokesman Devin O'Malley criticized the judge's decision.
"The District Court exceeded its authority today when it barred the President from instructing his cabinet members to enforce existing law," he said.
"The Justice Department will vindicate the president's lawful authority to direct the executive branch."
San Francisco Attorney Dennis Herrera called the ruling "a victory for the American people and the rule of law."
"The only way to stop a bully is to stand up to him," Herrera said. "That's what San Francisco has done."
Trump's administration could try to push the issue to the Supreme Court.