A defect in the water-inlet valve may mean that it's no longer able to shut off completely when the electricity has been turned off to it. If this occurs, the valve may leak and drip water into the clothes tub. In time, the water may accumulate substantially. If this happens, you need to replace the valve.
A defect--or an obstruction--in the water-level switch may mean that it can't tell the water to shut off. So the machine overflows. This switch senses the water level in the clothes tub. It's usually a diaphragm device with a small, clear tube attached between the switch and the bottom of the washer's outer tub. As the water level in the tub increases, the pressure on the air in the tube increases. When the pressure reaches a certain level, it activates the switch, shuts off the water, and signals the timer to begin the agitate cycle. You can either clear any obstruction in the tube or replace the water-level switch.