To incorporate this type of server validation you will need to make sure you have a recordset on the page that pulls the stock value from your db. This recordset will need to be above the validation code.
Once the recordset is in place you will add in the validation. The validation will be a number validation. For the value use the lightning bolt to select the quantity field then add the validation. You can leave the minimum at 0 but for the max you want to use the value from your recordset for the stock level. I'm including a screen shot of what this validation looks like when configured in the interface.
So long as this recordset occurs before the validation does then this should work for you. One other thing is the validation trigger, it should be setup like you add to cart, probably the button pressed trigger.