Made isValid much more robust and less prone to edge cases.