Add name validation and optimize code