The law came into effect in July in a bid to end "rent-a-womb" tourism in Thailand following a series of high-profile surrogacy cases involving foreigners, including accusations in 2014 that an Australian couple had abandoned their Down syndrome baby with his Thai birth mother.
Thailand had been a popular destination for foreigners seeking surrogacy services, in part because of lower prices but also because of the country's lax legislation.
American Gordon Lake and his Spanish husband, Manuel Santos, had a baby called Carmen through a Thai mother before the Thai ban on commercial surrogacy came into effect.
A bitter battled ensued when surrogate mother Patidta Kusolsand refused to cede parental rights to the couple leaving them trapped in Thailand with Carmen.
Manuel, speaking to reporters outside a Bangkok family court after the verdict, said the couple would take Carmen to Spain first to meet her family there.
"This nightmare is going to end soon," Santos said through tears. "Carmen will be with us in our home."
Patidta had said she did not know the couple were gay and was unsure about their abilities as parents.
The pair have another child, son Alvaro, who was born through surrogacy in India three years ago, and have said they chose Thailand because regulations in India had changed.
Santos said he could not confirm when the pair would leave Thailand with their two children.