Valency is combining the capacity of an atom. i.e. the number of electrons given or taken by an atom for attaining the duplet or octet configuration (8 electrons in outer orbit).
Oxygen has 8 electrons. The electronic configuration is 2,6. i.e. it has 6 electrons in outer most orbit and it needs 2 more electrons to attain octet. Hence its valency is 2.
Magnesium has 8 electrons. The electronic configuration is 2,8, 2. i.e. it has 2 electrons in outer most orbit. Therefore, it will be easy to lose 2 electrons to attain octet instead of gaining 6 electrons. So it loses 2 electrons. Hence the valency is 2.
Note: Valency is always positive.