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
Sayyiduna Ubadah bin al-Samit (may Allah be pleased with him) said that the Messenger of Allah (peace and blessings be upon him) forbade separating a mother from her child. It was said: O Messenger of Allah, until when? He said: "Until the boy reaches puberty and the girl begins to menstruate."
Hadith Referenceالسنن الكبرى للبيهقي / كتاب السير / 18326
Abu al-Hasan al-Daraqutni (may Allah have mercy on him) said: This Abdullah bin Amr is al-Waqifi, and he is da'if (weak) in hadith. Ali bin al-Madini accused him of lying, and no one other than him narrated it from Sa'id.
Hadith Referenceالسنن الكبرى للبيهقي / كتاب السير / 18327