There's a ton of questions about this particular exception but I couldn't find any that would suit my needs. I don't want to disable validation and neither wouldn't want to manually escape each form input value.
Is there a way to display this error message to the user in the same way as ASP.NET MVC informs the user of not providing a required value in the form? I think this would be the cleanest way to deal with this kind of error.
-
are you using jQuery? Not tagged, but I can think of a solution client side that would probably workhunter– hunter2011年09月07日 13:46:53 +00:00Commented Sep 7, 2011 at 13:46
-
I can use jQuery but wouldn't like to write own validation logic for them because if some kind of new potentially dangerous value validation is added to ASP.NET MVC, it would be missing from my implementation.Ville Salonen– Ville Salonen2011年09月07日 13:53:56 +00:00Commented Sep 7, 2011 at 13:53
-
Plus there's always a possibility that someone is using my site without JavaScript support and they would be send to a generic "Internal server error" page which wouldn't tell them anything.Ville Salonen– Ville Salonen2011年09月07日 13:54:36 +00:00Commented Sep 7, 2011 at 13:54
-
See my answer... that should be close. You may need some tweaking here and there for line breaks in textareas.hunter– hunter2011年09月07日 13:55:04 +00:00Commented Sep 7, 2011 at 13:55
-
Well, if you don't want to turn off request validation, how do you think you can accomplish this server-side?hunter– hunter2011年09月07日 13:55:50 +00:00Commented Sep 7, 2011 at 13:55
2 Answers 2
$("form").submit(function(e){
var invalid = $("form").find("input:text,input:hidden,textarea").filter(function() {
var value = $(this).val();
var encoded = $("<div>").html(value).text();
return value != encoded;
}).length > 0;
if (invalid)
{
e.preventDefault();
//show validation message
}
}
Comments
This error is just a safety net in ASP.NET; Microsoft would expect you to disable this error once you've checked you are encoding your text properly.
It's not about manually escaping each input form value. It's about HTML encoding all user-facing text that is rendered to the page. It's just that text that is entered in forms is frequently displayed back to the user.
For example, the string "My age is > 21 & < 90" is not valid HTML and won't appear correctly to the user (this could be abused in a cross-site script attack). If any string you are displaying is not already valid HTML, you have to HTML-encode it. Fortunately in MVC there are plenty of easy ways to do this (using <%: %> operators is one). If you are doing this correctly, then there is no need to have this error enabled.
Sorry I know this isn't the answer you asked for, but I believe keeping this error switched on is just user-unfriendly for many reasons.