Valency is the no of electrons that an atom looses /gain or share to form a stable compund
Valency can also be defined as no. of electrons present in outermost shell(valence shell)
If is lesser than 4 than no of electrons is valency. If it is greater than 4 than subtract no of electrons from 8 to get valency.
Example: Magnesium has electronic configuration 2,8,2. Its valence shell has 2 electrons. As 2 is lesser than 4, the valency of Magnesium is 2.
valency of oxygen is 2 as its electronic configuration is 2,6 and it need 2 electron to complete their octet.