Moved validate code into a function.