replace valid() function
v2 Passing all tests