The valency is defined as the number of electrons gain or lost by an atom.
The electrons present in the last shell determine the valency of a particular element.
If,
Number of valence electrons ≤4: valency = number of valence electrons
Number of valence electrons >4: valency = 8 - number of valence electrons
If you consider the element ‘aluminium’ and try to write its electronic configuration, then it is 2, 8, 3 the valency is equal to 3.
However, for element ‘oxygen’ having electronic configuration 2, 6 the valency is 8 – 6 = 2.
I don't think there is a particular formula for finding valency.
To find the valency, just write the electronic configuration and then proceed as mentioned above