Restructured validation code to be a bit cleaner to read and testable