Answer:
the valency of an element is its combining capacity that is the number of electrons it requires to lose, gain or share in order to become neutral.
[ 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 ]
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.