All perfect praise be to Allaah, The Lord of the Worlds. I testify that there is none worthy of worship except Allaah and that Muhammad, sallallaahu ʻalayhi wa sallam, is His slave and Messenger.
When the person goes to the mosque with no intention of performing prayer and then performs the prayer therein, his prayer is valid; as is the case when the person goes outdoors to have a walk and enjoy the good weather and then happens to pass by a mosque and decides to go inside and perform the prayer. His prayer is valid in such case.
The same applies if he goes to the mosque to meet someone and when he arrives there an obligatory prayer becomes due so he performs it in the mosque or the like; his prayer is valid in that case as well.
However, he misses the rewards for going to the mosque, which were highlighted in the hadeeth that reads, “...if he performs ablution as due and then goes to the mosque with the sole intention of performing the prayer, then with every step that he takes to the mosque, he will be raised one degree or one of his sins will be forgiven...” [Al-Bukhari] The version cited by Imaam Muslim reads, “...and he is impelled (to do so) only by (the love of attending the congregational) prayer, he has no other objective but to perform the prayer...”
Allaah knows best.