As one moves from left to right in a period, the electrons keep on increasing by 1, i.e. the valence electrons keep on increasing . So the elements with valence electrons less than 5 , i.e. 1-4 have the valency same as the no. of valence electrons. E.g. valence el in Al are 3 in the M shell, so valency is 3. But elements with valence electrons 5-8 obtain their valency by subtracting it from 8. E.g. Cl has 7 valence electrons so its valency=8-7=1.
As we move down a group (vertically), the valency remains the same.