Sergio Busquets scored with virtually the last kick of the game to get Barcelona back within two points of league leaders Real Madrid.
Barcelona looked set to lose ground in the title race but deep into injury time Lionel Messi set up Busquets to net his first goal for 14 months.
Valencia slip to fifth in La Liga after their first home defeat of the season.
Messi was struck on the head by something seemingly thrown from the crowd during the celebrations.
He was pictured rubbing his head afterwards, but appeared to be unhurt.
It was a win that for so long looked unlikely, with Barcelona coach Luis Enrique having selected both Busquets and Javier Mascherano in central midfield, and the visitors suffered from a rare lack of creativity.
But Busquets justified the decision in dramatic style, following up to volley home from close range after Diego Alves had saved Neymar's header from a Messi cross.
Former Liverpool striker Luis Suarez had earlier missed Barcelona's best two opportunities and also had an effort incorrectly ruled out for off-side when turning in an attempted Dani Alves shot.
Valencia, who have not beaten Barcelona at home since 2007, had chances of their own to win it but for the second successive home game were unable to score.
In the final minute of the first half, Andre Gomes rounded Barcelona goalkeeper Claudio Bravo but shot into the side netting from a tight angle.
After the break the home side had further chances to damage Barcelona's title prospects but Gerard Pique cleared off the line from Rodrigo.
With 20 minutes to go Bravo saved from Sofiane Feghouli and then thwarted on-loan Manchester City striker Alvaro Negredo.
And Valencia were denied even a point when Busquets became the unlikely match-winner, sparking celebrations which saw Messi booked after he was hit on the head by an object as Barcelona players celebrated the dramatic winner.