As mentioned by Zhe, we have to look at the entire process by which an ionic compound is formed, not just the energy for a single part.
For example, consider the formation reaction of $\ce{MgO}$
$$\ce{Mg(s) +1/2O2(g)->MgO}$$ To find the enthalpy of this process, we could follow a Born-Haber cycle: 
This demonstrates that while the ionization of $\ce{Mg}$ to $\ce{Mg^{2+}}$ might be unfavorable, the overall process to form the compound is not. So the ionization of $\ce{Mg}$ is driven by the favorability of the overall process.2
It is also worth noting why we do not instead form $\ce{Mg2O}$. If we were to construct a Born-Haber cycle for this compound, it would take less energy to form $\ce{2Mg^{+}(g) +O^{2-}(g)}$ than it would to form $\ce{Mg^{2+} (g) + O^{2-}(g)}$. However, the lattice energy of $\ce{Mg2O}$ would be sufficiently smaller than the lattice energy of $\ce{MgO}$ that $\ce{MgO}$ is still more favorable to form. Lattice energies are heavily dependent on the charge of the ions involved and having a $+2$ ion will lead to twice as large a lattice energy as an ion with a $+1$ charge all else being equal.
Even in this simple case, all else might not be equal. To make a more direct comparison between we can utilize the Born-Lande or Born-Mayer to obtain a calculated value of the lattice energy.