<em>the <u>valency of an element</u> is its combining capacity that is the number of electrons it requires to lose, gain or share in order to become neutral.</em>
[ An element can become neutral if it completes it's octet. That is if an element has 8 electrons in it'd outermost shell then it is considered neutral ]
The valence of Magnesium is 2 because it requires to lose 2 electrons to become neutral.
whereas, the valence of Oxygen is 2 because it needs to gain 2 electrons to become stable.
Hence they both have the same valence.
One may say that oxygen's valence is -2 while that of Magnesium is + 2. It's meaning is still the same but "-" sign indicates that oxygen will be gaining electrons in the process of becoming stable.