Praise be to Allah.
In the answer to question no. 2571, we stated that it is prohibited to masturbate during the day in Ramadan, and if a person masturbates and emits maniy, then his fast is invalidated.
You should have delayed that until nighttime – if possible – so that you would not invalidate your fast without an excuse. If that was not possible, then there is no blame on you for what you did, but you have to do make up that day’s fast.
It says in Fataawa al-Lajnah ad-Daa’imah, vol. 1 (24/436):
My question is about the ruling on doing the secret habit in the hospital laboratory for the purpose of providing a sample in the case of infertility problems, as the sample must be handed over to the lab ten minutes after emission of maniy, because the sample is not acceptable a long time after emission. Hence we hope that you can give us a fatwa explaining the ruling on doing the secret habit for the purpose of providing medical samples in the case of infertility problems or other illnesses which require a sample of semen to be tested in the lab.
After studying the matter, the committee replied:
Because of the urgent need for that, and because the interests that it is hoped will be served by that outweigh the negative consequences of masturbation, that is permissible. End quote.
For more information, please see the answer to question no. 27112
It says in Fataawa al-Lajnah ad-Daa’imah, vol. 1 (10/261):
In Ramadan 1410 AH, I had a check-up in the hospital. At that time I did not have any work opportunities. When I went to the doctor, he asked me for a sample of semen, and the doctor told me that this was essential, which compelled me to do that so that I could give them the sample for testing. That was during the day in Ramadan, and was done by means of masturbation. Please note that I did not have any other opportunity to go back to the hospital, and on the day when I went there it was an appointment made by the hospital. That was for testing for me and my wife.
I hope that you can give me a fatwa about this matter, and tell me whether I need to offer any expiation other than making up that day, so that I may know what to do.
Answer: If the matter is as described, then you have to make up the fast of the day on which you masturbated, but you do not have to offer any expiation. End quote.
And Allah knows best.