由於在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="[email protected]" }) %>
<%= Html.ValidationMessageFor(model => model.Email) %>
</div>
<input type="submit" value="Send" />
</fieldset>
</form>
通知行:if (Request.QueryString["error"] == "1"
處理在重定向中的Application_Error
傳遞的參數到目前爲止,我們有服務器端驗證。
對於客戶端驗證,我們添加使用JQuery驗證插件自定義規則:
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;
}