Improved IsValidKey logic.