Imam al-Shafi'i (may Allah have mercy on him) said: "When the child reaches seven or eight years of age." He drew an analogy for this with the time at which (a child) chooses between the two parents, and with what has been narrated on this from Sayyiduna Ali (may Allah be pleased with him).
In the narration of Harmalah he said: "Until he reaches puberty."
The Shaykh (Imam al-Bayhaqi) (may Allah have mercy on him) said: "A weak hadith has also been narrated on this."
Hadith Referenceالسنن الكبرى للبيهقي / كتاب السير / Q18326