The home side led 2-0 until just past the hour mark, but two own goals and a fine finish from the Argentine sealed a priceless three points for Gerardo Martino's men
The champions trailed 2-0 after the first hour thanks to goals from Cani and Trigueros, but two own goals from Gabriel Paulista and Mateo Musacchio put Gerardo Martino's men back in the contest.
And with just 12 minutes to play, Messi finished a fine team move involving Sergio Busquets and Cesc Fabregas to secure a priceless three points for the Blaugrana at the end of a deeply emotional week for the Catalan club.
Sergio Busquets struggled to hold back tears during the emotional minute's silence which preceded the match in honour of Tito Vilanova, who lost his battle with cancer this week. The Villarreal team donned shirts which paid homage to the late Barcelona boss.
The early proceedings were understandably subdued, but Messi had the first chance of the game in the 17th minute, with Asenjo producing an important save with his feet.
Barca continued to dominate possession, as usual, although Giovani dos Santos – who came through the ranks at Camp Nou – was unable to punish his former side at the other end after a quick Villarreal break, with Marc Bartra blocking a shot on the line.
The hosts then claimed the lead on the stroke of half-time, as Cani coolly slotted his first-time shot into the bottom-right corner after collecting Jonathan Pereira's precise ball.
Barcelona began the second half in impressive fashion and looked likely to draw level as Messi's influence on the game grew.
The forward first saw a 25-yard curling effort palmed away by Asenjo, before the goalkeeper kept out two free kick attempts from the Argentina star.
Villarreal were able to double their lead, though, as Trigueros rose brilliantly to steer a pinpoint header past Jose Manuel Pinto from Javier Aquino's cross.
Barcelona finally scored in the 65th minute, with Gabriel diverting Dani Alves' cut-back past his goalkeeper.
Another own goal was to follow, as Barca equalized after Musacchio headed Alves' delivery beyond Asenjo's reach.
And they completed their unlikely comeback in the 83rd minute, as Busquets' lofted ball was headed across by Fabregas, with Messi on hand to steer the winner home.
The match was soured by a banana being thrown at Alves during the second half, which the Brazilian proceeded to pick up and eat before taking a corner.
Barcelona are now four points behind leaders Atletico Madrid - who they play on the final day of the season - with three games to go, after Diego Simeone's side beat Valencia 1-0 earlier on Sunday.