HTML code here
Most users don't like surprises, especially annoying ones that create more work or prevent them from accomplishing their goals.
Validate user input as soon as possible and show any validation messages in line with the thing being validated.
As a general rule, the more immediately you can validate input from people and provide feedback related to it, the better. This is because the people are already focused on the thing being validated (or just finished with it), so the context is still immediate and fresh in their minds. Showing the messages in line with the thing being validated reinforces that context so people don't have to draw a mental line between a validation message and the problem input.
Trigger validation immediately after an input loses focus. Sometimes it makes sense to validate immediately (such as on key up or upon choosing some option), but you don't want to lock people into an input loop as that can be very frustrating.
Perform the validation asynchronously if it will take more than a few milliseconds. If it could take some time, you may want to rethink this approach. If it is not almost immediate, the effect of seemingly randomly displaying a validation message would be more surprising and confusing than if it occurs upon some indication to the user that they are done (such as clicking a "submit" button). If it takes a second or so, consider showing some sort of "working" message to let people know that the system is doing it; that way the user is expecting a result to appear when it does and may even pause for a few seconds to keep their focus on it.
Show the validation problem messages in line with the elements they are validating. It's best to show the message (and not just some sort of indicator like an asterisk or exclamation mark) with the problem field if there is room, but if you have to separate them, you need to show the message in some consistent place that will be in people's view and also show an indicator next to problem fields.