Praise be to Allah.
Whoever thinks about sex and ejaculates, or has a wet dream and ejaculates, that does not invalidate his fast, but he has to do ghusl from janaabah, because when Umm Sulaym asked him, “Does a woman have to do ghusl if she has a wet dream?” the Prophet (peace and blessings of Allaah be upon him) said, “Yes, if she sees water.”
The same ruling applies to men, because the Prophet (peace and blessings of Allaah be upon him) said: “Water is for water.”
With regard to his fast, it is valid, because a wet dream is not something that happens by choice. Similarly, thinking is something which is forgiven by Allaah, because the Prophet (peace and blessings of Allaah be upon him) said: “Allaah has forgiven my ummah for wrong thoughts that cross their minds, so long as they do not speak of them or act upon them.”
This is all kindness from Allaah.