The valency of an element can be said in 2 ways depending on its outer-most electron shell.
First of all, the number of valence electrons (number of electrons in the outer-most shell) can be determined by either looking at the group (column number) in which the element is situated in the Periodic Table.
Now, after finding the number of valence electron, if the number is lesser than 4, the valency of the element is the same as the number of valence electrons. If the number of valence electrons are greater that 4, then you subtract the number of valence electrons from 8 (number of electrons in a complete outer shell) to calculate the valency of the element.
Examples:
Valency of Magnesium:
Magnesium is located in Group 2 and therefore has 2 valence electrons. It also has electron configuration of 2.8.2 and the last 2 (in bold) shows the number of valence electrons. As 2 is lesser than 4, the valency of Magnesium is 2.
Valency of Oxygen:
Oxygen is located in Group 6 and therefore has 6 valence electrons. It also has electron configuration of 2.6 and the last 6 (in bold) shows the number of valence electrons. As 6 is lesser than 4, the valency of Magnesium is 8 - 6 = 2.