Refactor 'is_valid_key' function