As with any other injection vulnerability, a proper input validation is the first line of defense in order to prevent XSS. Also, if possible, avoid using user inputs as output information. Sanitization and encoding are key aspects of preventing XSS.
Sanitization means removing inadmissible characters from the string. This is useful when no special characters should exist in input strings.
Encoding converts special characters to their HTML code representation. For example, & to & or < to <. Some types of applications may need to allow the use of special characters in input strings. For those applications, sanitization is not an option. Thus, they should encode the output data before inserting it into the page and storing it in the database.
The validation, sanitization, and encoding processes must be done on both...