This is a deep and important question. You can indeed be following all the formal "rules" - laws, religious doctrines, ethical guidelines - and still act wrongly. Here's why:
1. Rules can't capture every situation's nuance and context
2. Different systems of rules sometimes conflict with each other
3. Rules can themselves be flawed or unjust
4. Blind rule-following without moral reasoning can lead to harmful outcomes
Consider historical examples where laws supported slavery or segregation - following those laws would have been legally correct but morally wrong. Or cases where strict religious adherence led to harming others in the name of doctrine.
What ultimately matters is developing sound moral judgment and wisdom to navigate complex situations, rather than just checking boxes of compliance. Sometimes doing the right thing requires going beyond or even against established rules.