Bojan Krkic scored two second-half goals and set up the other two for Barcelona on Sunday.
Madrid, which had been trying to maintain its seven-point lead at the top of the standings, lost at home when Javier Arizmendi scored in the 89th minute.
Arizmendi outran Fabio Cannavaro to a long ball and then got around the Madrid defender before sliding his shot past goalkeeper Iker Casillas inside the far post.
Madrid still leads the league with 62 points, followed by Barcelona with 58. Villarreal, which beat last-place Levante 2-1 on Guillermo Franco’s 83rd-minute goal, is third with 56 points.
David Villa scored two goals, one from the penalty spot, for Valencia, which also reached the Copa del Rey final by beating Barcelona. Villa gave the visitors the lead in the 34th from a Madrid turnover, but Raul Gonzalez headed in an equalizer in the 35th.
Raul scored his 15th goal by tipping Jose Maria “Guti” Gutierrez’s short pass at the penalty spot in the 56th and volleying it past Valencia goalkeeper Timo Hildebrand. Hildebrand made up for that miss 10 minutes later when he dove to catch Sergio Ramos’ header on the goal line.
Cannavaro then pushed David Silva inside the area and Villa took the penalty, catching Casillas going the other way in the 67th. Hildebrand twice stopped shots from substitute Gonzalo Higuain - first from a header, then on the rebound - in the 80th, and Raul Albiol cleared an angled shot from the Argentine forward off the line with three minutes left.
The Germany goalkeeper then swiped Raul’s point-blank header over the bar a minute into injury time. Valencia defender Carlos Marchena was taken to the hospital after being hit in the head by Guti’s 29th-minute free kick.
The Spain international laid on the field for several minutes before being stretchered off with what appeared to be concussion.
With Barcelona already leading 2-1, Krkic pounced on a loose ball in the box in the 61st minute and rolled it under goalkeeper Sergio Asenjo. The 17-year-old striker tapped in Samuel Eto’o’s pass at the far post for his seventh of the season in the 84th. Andres Iniesta and Eto’o also scored for Barcelona.