You can only name a Pokemon if it was caught by you. If you have a Pokemon from a different trainer but with a similar trainer ID to you, the game won't be fooled as each trainer ID comes with a secret ID that is assigned to all Pokemon caught by the original trainer. The secret ID is generated for the sole purpose of making sure Pokemon are still treated as outsider Pokemon in games where the trainer has a matching trainer ID.
If the Pokemon has the same trainer ID, Secret ID, OT and OT gender then it will not be treated as an outsider Pokemon, thus allowing you to rename it.
Hope I helped. :)