Messi bent a stunning free-kick into the top corner in the 90th minute after Villarreal's Italian forward Nicola Sansone finished off a breakaway to open the scoring in the 50th as they looked set to record a first home win over Barca in 11 years.
Barcelona have 35 points from 17 games, one behind Sevilla, and trail a Real Madrid side who beat Granada 5-0 on Saturday, are unbeaten in all competitions and have a game in hand.
"I can't make a positive evaluation because we needed the three points today," said Barca coach Luis Enrique. "We aren't on a very favourable run at the moment and although we kept hitting the target things just would not fall for us."
The pressure was on Luis Enrique's side after Real and Sevilla enjoyed big wins on Saturday but Villarreal were far from ideal opponents, having held Barca to a 2-2 draw last season and halting their 12-game winning streak in the league.
The first clear chance of a vibrant, end-to-end game fell to former Barcelona midfielder Jonathan dos Santos, who put too much power on his shot and watched it fly over the bar.
Luis Enrique made three changes to the Barca team that lost 2-1 in a King's Cup last 16, first leg game at Athletic Bilbao on Thursday and it was one of the players he recalled who made the fatal mistake that led to the opening goal.
Messi hit the post with a sumptuous shot and had a penalty appeal turned down when his effort was blocked by Villarreal captain Bruno Soriano's hand, while Barca's Javier Mascherano was also fortunate not to concede a spot kick for handball.