由于在 TextArea 中输入 html 会引发 HttpRequestValidationException 异常,因此在管道的早期,我们只能在 Global.asax 中将其与未处理的异常一起捕获。
在 Global.asax.cs 我们添加:
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
ex = ex.InnerException ?? ex;
if (ex is HttpRequestValidationException)
{
string url = Request.Url.ToString() + "?error=1";
Response.Redirect(url);
Server.ClearError();
return;
}
//any other exception handling that you need goes here
}
这里是标记:
<form action="<%=Url.Action("Create") %>" method="post" class="data-entry-form" id="feedBackForm">
<fieldset class="comment">
<div class="editor-field">
<%= Html.TextAreaFor(model => model.Comment, 10, 2, new { placeholder="your message" }) %>
<%= Html.ValidationMessageFor(model => model.Comment) %>
<% if (Request.QueryString["error"] == "1")
{
Response.Write("<br/><span class= 'error'>Please remove all HTML from your comment and resubmit</span>");
} %></div>
<br />
E-mail address (optional)
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Email, new { placeholder="you@youremailaddress.com" }) %>
<%= Html.ValidationMessageFor(model => model.Email) %>
</div>
<input type="submit" value="Send" />
</fieldset>
</form>
注意这一行:if (Request.QueryString["error"] == "1" 在 Application_error 中处理重定向中传递的参数
到目前为止,我们已经进行了服务器端验证。
对于客户端验证,我们使用 JQuery Validate 插件添加自定义规则:
jQuery.validator.addMethod("hasNoHTML", function (value, element) {
if (value.match(/<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/)) {
return false;
}
return true;
}, "* Please remove all HTML from your comment and resubmit");
$("#feedBackForm").validate(
{
rules: {
Comment: {
required: true,
hasNoHTML: true
}
}
}
);
这里是对正则表达式的引用:http://ejohn.org/files/htmlparser.js
以及装饰错误的css:
.error {
color:red;
}