How to validate before submitting form values?

How to validate before submitting form values?

I have a submit button on my form.  However, I would like to do validation before submitting. 
I would submit the  form values only if the validation has passed. 
 
How can I do that? Can I have an example please.
 
I have the following code:
  1. <input type ="text" id="password"/> <input type="text" id="confirmPassword"/><label for="err"></label><input type="submit" value=Save/>