All perfect praise be to Allah, The Lord of the Worlds, and may His peace and blessings be upon out Prophet Mohammad and upon all his family and companions.
In principle, observing I`tikaaf (seclusion in the mosque for the purpose of worship) in the mosque is a confirmed act of Sunna which is recommended at all times. This act of Sunna becomes more confirmed when observed in the last ten days of Ramadan because a worshipper follows the Sunna of the Prophet and gets the reward of the night of decree.
There are two types of I`tikaaf: Obligatory and voluntary. Obligatory I`tikaaf is the vowed I`tikaaf; therefore, whoever vowed to observe I`tikaaf in the mosque for a number of consecutive days is obliged to do so. However, he is allowed to leave the mosque to eat and answer the call of nature, even if he could do that at the mosque`s utilities, but if he makes love to his wife, then his I`tikaaf is considered invalid and he is obliged to do it all over again from the very beginning. Allah, The Almighty, Said in this regard, (What means): "but do not associate with your wives while ye are in retreat in the mosques." [Al-Baqarah/187].
It is stated in "Umdat Assalik", a Shafi book: "I`tikaaf is nullified by having sexual intercourse with one`s wife and a worshiper who vows to observe I`tikaaf for a consecutive period of time is obliged to do so. However, if he leaves the mosque to eat, even if he could eat in the mosque, or to drink water, even if there was no water in the mosque, or to answer the call of nature, or due to sickness or menses (woman) and the like, then the I`tikaaf is valid."
Voluntary I`tikaaf: If the worshiper observing this type of I`tikaaf leaves the mosque to eat or to go to the toilet of his home, and he makes love to his wife, then his I`tikaaf is discontinued and he is obliged to take a ritual bath (Ghusl). However, he is rewarded for the part of I`tikaaf that he did before he took the ritual bath, and if he decides to redo I`tikaaf, then he can, but with a new intention.
It is stated in [Moghni al-Mohtajj] a Shafi book: "If he made love to his wife outside the mosque while he was observing vowed obligatory I`tikaaf, then it is unlawful, but if it was voluntary I`tikaaf, then it is lawful because his intention is to get out of that act of worship, and this is permissible. In voluntary I`tikaaf, his I`tikaaf before having sex with his wife is valid; whereas, in consecutive vowed obligatory I`tikaaf, it is invalid. However, if the I`tikaaf wasn`t consecutive, then the part observed before making love is valid, whether the I`tikaaf was vowed or voluntary." And Allah Knows Best.