XSS is to do with failed output escaping, not input length. Even if the length check were done properly, the minimum length of input that might provoke an XSS attack is one character: <. For example if the userName were echoed to the page just before a string script which is, by itself, innocuous.
–
bobinceFeb 7 '13 at 12:59

2 Answers
2

Your solution doesn't prevent any XSS attack. The HTML input tag attribute maxlength is an instruction to the web browser, that a malicious attacker can trivially change in any modern browser by dynamically altering the DOM.

<input name="userName" type="text" id="userID" maxlength="8"/>

Your sanitation routines have to be done with server-side code. That is this type of sanitation could be done if you truncate any input that's longer than ~8 characters when in your server-side code (not in the HTML attribute that a client can easily modify). Beware that html/js is quite forgiving (and you'd have to test all browsers), so once you get to lengths of more than len(<script>) ~ 8, I think this mechanism likely could fail for some clever use with some bad browsers.

However, this is still an inane route to preventing XSS (unless the only data your application will ever take and possibly ever display back to any user is 8 characters and your server side code truncates this user input at ~8 char). You really need to either:

First escape all the special html characters in user input ("&'<> to their HTML escaped versions: &quot;&amp;&apos;&lt;&gt;) and then apply rules of a safe lightweight markup language (like reddit markdown) to only allow safe things like links[links](http://example.com) (checking the protocol is in your safe whitelist e.g., http/https/ftp) or italicized (*italicized*) or bold (**bold**) text.