Improve isInvalid function