Refactor validation function