C#的自定义RequestValidator

时间:2018-08-30 10:51:43

标签: c# asp.net

我正在处理asp.net应用程序。我需要使用重写RequestValidator处理一些HTML标记。我已经做到了。

<asp:textbox runat="server" ID="1stTextbox" />
<asp:textbox runat="server" ID="2ndTextbox" />

我有这些文本框,我需要从此处为这些文本框设置值。有什么办法,我可以从这里设置控件的值。这样,我们可以在将其发布到服务器/数据库之前进行编辑。

using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Util;

public class CustomRequestValidation : RequestValidator
{
string[] textControlsArray = { "1stTextbox", "2ndTextbox" };

protected override bool IsValidRequestString(HttpContext context, 
    string value, 
    RequestValidationSource requestValidationSource,
    string collectionKey,
    out int validationFailureIndex)
{
    validationFailureIndex = -1;  //Set a default value for the out parameter.

    //This application does not use RawUrl directly so we can ignore the check.
    if (requestValidationSource == RequestValidationSource.RawUrl || requestValidationSource == RequestValidationSource.Cookies
        || requestValidationSource == RequestValidationSource.Headers || requestValidationSource == RequestValidationSource.Files)
        return true;

    //Allow the form data to have a value that is formatted like HTML entry.
    if (requestValidationSource == RequestValidationSource.Form && textControlsArray.Contains(collectionKey))
    {
        if (value.Contains("<") && value.Contains(">"))
        {
            int startIndex = value.IndexOf("<") + 1;
            int lastIndex = value.IndexOf(">");

            value = value.Substring(startIndex, lastIndex - startIndex);

            if (IsValidEmail(value))
            {
                validationFailureIndex = -1;
                return true;
            }
            return base.IsValidRequestString(context, value,requestValidationSource, collectionKey, out validationFailureIndex);
        }
        else
            //Leave any further checks to ASP.NET.
            return base.IsValidRequestString(context, value,
            requestValidationSource,
            collectionKey, out validationFailureIndex);
    }
    //All other HTTP input checks are left to the base ASP.NET implementation.
    else
    {
        return base.IsValidRequestString(context, value, requestValidationSource,
                                         collectionKey, out validationFailureIndex);
    }
}

private bool IsValidEmail(string strEmail)
{
    if (String.IsNullOrEmpty(strEmail))
        return false;

    // Return true if strIn is in valid e-mail format.
    return Regex.IsMatch(strEmail,
           @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
           @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
           RegexOptions.IgnoreCase);
}

}

0 个答案:

没有答案