After a goalless first half, the visitors made the breakthrough in the 65th minute when Santi Cazorla found the bottom corner from outside of the box.
Villarreal were level in the 82nd minute as Carlos Kameni was shown a red card for Malaga for his foul on Hernan Perez inside the area. Marcos Senna smashed his spot kick into the top corner to make it 1-1.
However, there was time for a winner when Perez struck deep into added time to give his side a vital three points.
Villarreal are now seven points clear of the drop zone, while Malaga stay fourth.