In the first place, we would like to stress that Muslims should, of course, choose an Imam of good character, and the community should have at its disposal means to remove an Imam if there is no way to change his misbehaviour after exerting efforts and sincerely advising him.
However, if in some situations a Muslim finds a person whom he thinks to be impious leading the prayer he should not refuse to pray behind him. This is based on the Hadith in which the Prophet (peace and blessings be upon him) is reported to have said, “Prayer is a necessary duty for you behind any Muslim, pious or impious, even if he commits heinous sins.” (Reported by Abu Dawud)
Moreover, it is the duty of the Imam to withdraw himself from leading others in prayer as soon as he realizes that a majority of the people who pray behind him do not wish him to be their Imam.
Sheikh Ahmad Kutty, a senior lecturer and Islamic scholar at the Islamic Institute of Toronto, Ontario, Canada, states the following: “If someone is in the habit of watching pornographic pictures, movies, nude women, etc., We are certainly not allowed to put him forward as an Imam to lead the salah. Such a person is flaunting the Laws of Allah, and as the Prophet (peace and blessings be upon him) said, “All of my Ummah will be forgiven of their sins except those who flaunt their sins.”
If, however, such a person happened to lead salah and you found yourself left with no choice but to pray behind him (because of finding no other jama`ah in the vicinity to you which you can join), then your prayer is valid and acceptable. However, that does not absolve the congregation of their duty to remove the person and choose someone who is pious and knowledgeable as an Imam. We must choose our leaders based on their knowledge as well as their probity and integrity.
The Prophet (peace and blessings be upon him) is reported to have said: “There are three persons whose prayer will not rise above their heads (i.e. will not ascend to Allah): One of them is a person who leads people in salah while they actually hate him (because of his conduct).”
According to Imam Khattabi, the Hadith applies to a person who steps forward to lead people in salah while he himself does not possess the necessary qualifications of an Imam. Such qualifications include knowledge as well as piety.
If a brother continues to sin, then others have a duty to advise him first. If he still does not desist, then they must warn him of the dire consequences of his actions. Simply keeping quiet about sins will only expose us to the Wrath of Allah. When Allah’s punishment comes, it will not make a distinction between the sinners and others, since we are obligated not only to abstain from sins by ourselves but also to counsel others against them.”