Vinicius Jr collected Karim Benzema’s pass and his strike deflected in at the near post on 86 minutes.
Just two minutes later the roles were reversed as Brazilian Vinicius sent in a cross for Frenchman Benzema to head in his sixth goal of the season.
Valencia had gone ahead when Hugo Duro drilled a precise finish into the corner but they could not hang on.
Valencia had the better chances in the contest and forced Real goalkeeper Thibaut Courtois to make a superb reaction save to deny Gabriel’s header, while Maxi Gomez curled a free-kick narrowly wide.
In the second half, Goncalo Guedes blazed over from the edge of the area before Duro broke the deadlock.
Real pushed forward late on and Vinicius’ curler straight at Giorgi Mamardashvili was a warning sign for the home side, who then conceded two late goals.
Real Madrid remain unbeaten under returning boss Carlos Ancelotti, winning four and drawing one of their games so far this season, while Valencia suffered their first defeat.