All perfect praise be to Allah, The Lord of The Worlds, and may His peace and blessings be upon our Prophet Muhammad and upon all of his family and companions.
In principle, a fasting person should draw closer to Allah through remembrance, invocation, performing acts of obedience and avoiding prohibited matters, such as staring at porn photos and using filthy language. This is to achieve the objective of fasting , be with the pious and righteous and avoid becoming one of those mentioned in the following narration: the Prophet (PBUH) said (What means): “There are people who fast and get nothing from their fast except hunger, and there are those who pray and get nothing from their prayer but a sleepless night.” [Al-Imam Ahmad]. In addition, masturbating-whether in Ramadan or any other time-is impermissible as has been clarified in the Fatwas (
891) and (
246).
Furthermore, masturbating during the day of Ramadan renders person’s fasting invalid. In this regard, Al-Imam An-Nawawi (May Allah have mercy on his soul) stated (What means): "If a person masturbates with his hand while fasting in Ramadan, then he has broken his fast according to the consensus of Shafie jurists.” [Al-Majmooa’ vol.6: P.322].
Therefore, one who did soshouldn’t break his fast during that day and he is obliged to make upfor that day. This is along with making repentance, asking Allah for forgiveness, showing remorse and determining to abandon masturbation. Further, this ruling applies on both the ignorant well as the one who is acquainted with the ruling of masturbating while fasting.
However, if the semen is ejected due to staring lustily to a photo without touching or making contact, then his fast is valid but he is obliged to repent from this sin. For further details, kindly refer to Al-Khateeb As-Shrbini`s book [Moghni Al-Muhtaj Vol. 2 : P.159]. And Allah The Almighty Knows Best.