【问题标题】:Global validation of text controls in an ASP.NET web forms applicationASP.NET Web 表单应用程序中文本控件的全局验证
【发布时间】:2013-10-28 22:31:58
【问题描述】:

我有一个旧版 ASP.NET 应用程序 (VS2005),它有大约 62 个页面和 84 个文本框控件分布在它们之间(每页 2 到 6 个文本框不等)。我想实施验证以防止提交会导致 XSS 漏洞的特殊字符。有没有办法一次性实现适用于整个应用程序中所有文本框控件的全局验证功能?(尽量避免每个文本框使用一个验证器,尽量减少对现有代码的更改)。

提前致谢

【问题讨论】:

  • 好吧,我认为您无法将网络表单中的内容发布到以< 开头的服务器。问题解决了;)
  • @Johan,提示:禁用事件验证?
  • @Johan 这不仅仅是

标签: c# jquery asp.net validation xss


【解决方案1】:

你可以使用继承来解决这个问题:

第一步:在基类中创建静态方法

// Return true if is in valid e-mail format.
public static bool IsValidEmail( string sEmail )
{       
    return Regex.IsMatch(sEmail, @"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"+ "@"+ @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");
}

第 2 步:为 Child 类中验证所需的所有文本框分配此方法

例子:

if (this.TextboxEmail.Text.Length > 0 && 
    IsValidEmail(this.TextboxEmail.Text) == false)
{
    ErrMssg("Invalid Email");
}

【讨论】:

  • 请再次阅读问题。这与所有页面中的电子邮件验证无关。
【解决方案2】:

您可以监听提交事件并在一个或多个文本框包含特定模式的情况下阻止它:

$(function(){

    $('form').on('submit', function(e){

        var $invalidTextboxes = $('input[type="text"]').filter(function(){
            return this.value.match(/abc+d/); //your pattern here
        });

        if($invalidTextboxes.length){
            alert('invalid textbox value');
            e.preventDefault();
        }

    });

});

如果您在页面上有更多表单,并且想要确定由 webforms 生成的表单:

How to capture submit event using jQuery in an ASP.NET application?

【讨论】:

    【解决方案3】:

    在全局级别执行验证的更好和通用的方法是借助 HTTP 模块

    您可以添加一个继承自模块类的新 c# 类。在类中,您可以在表单元素上添加迭代并执行所需的验证。这将帮助您在全局级别构建文本框验证的通用实现。

      class XssModule : IHttpModule
        {
    
            #region IHttpModule Members
            public void Init(HttpApplication application)
            {
              application.PostAcquireRequestState += new EventHandler(Application_PostAcquireRequestState);
            }
    
            public void Dispose()
            {
            }
    
            #endregion
    
            private void Application_PostAcquireRequestState(object sender, EventArgs e)
            {
    
                if (HttpContext.Current.Session != null)
                {
                 //Perform the iteration on the form elements here.                 
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 1970-01-01
      • 2012-06-21
      • 2021-07-14
      • 2011-03-02
      相关资源
      最近更新 更多