moved checkValid into a function