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 major impurity . When Umm Sulaym (may Allah be pleased with her) asked the Prophet (peace and blessings of Allah be upon him); Does a woman have to do Ghusl if she has a wet dream?, he said, “Yes, if she sees water.”
The same ruling applies to men, because the Prophet (peace and blessings of Allah 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 Allah, because the Prophet (peace and blessings of Allah be upon him) said: “Allah 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 Allah.
And Allah knows best.