You should know how many electrons fit in each shell.
K 2 L 8 M 2
You can fit 8 electrons in the M shell but after filling up the first shells, there are only 2 electrons left. This means that there are 2 valence electrons.
First, know that a valence electron is an electron in an outer shell. The Valence shell of the element magnesium contains a total of 2 Valence electrons.