“If another student is subjected to this discriminatory policy, that student can go to court, and has this decision to point to right away,” said Mr. Block, a senior staff attorney with the American Civil Liberties Union. “Other school districts in Virginia and around the country have been looking to see what happens with this case.”

A lawyer for Gloucester County Public Schools declined to comment on the decision on Friday.

A federal judge in Oregon last year said forcing transgender students to use bathrooms and locker rooms inconsistent with their gender identity would harm transgender students. An appellate court in Pennsylvania ruled in July 2018 in favor of a policy that supported transgender students, despite a challenge from other students who said sharing bathrooms with transgender students would infringe on their rights to privacy, among other laws.

“There has been striking uniformity over the past three years where judges who are confronted with real trans students, and real evidence, are finding that there is simply no basis for treating boys and girls who are transgender differently than other boys and girls,” Mr. Block said.

Judge Wright Allen’s ruling on Friday culminates a lengthy legal process in Mr. Grimm’s case.

He sued in July 2015. The school board argued in essence that its policy, adopted in 2014, was valid because Title IX of the Education Amendments of 1972 allows for claims only on the basis of sex, rather than gender identity, and that its policy did not violate the equal protection clause.

The case took a complicated path through the courts.

Partway through the proceedings, in March 2017, the Trump administration rescinded protections for transgender students.

The Supreme Court then vacated a prior appeals court decision in favor of Mr. Grimm and sent the case back to the federal appeals court in Virginia for further consideration in light of the new guidance from the Trump administration. The case was later returned to the District Court.

In May 2018, Judge Wright Allen, who was appointed to the bench by President Barack Obama, denied a motion by the school board to dismiss the lawsuit.