public static string FormatStr(string str)
    {
        string temp = "";
        temp = Regex.Replace(str, "[`~!@#$^&*()=|{}_':;',’#*\\[\\].<>/?~!@#¥……&*()—|{}【】‘;:”“'。,、?]", " ");
        return temp;
    }
这里验证非法字符,把非法字符替换成空,求更好的验证方法,本来想做个验证类,让input 继承这个类的验证方法,就不用像上边这样一个一个引用了各位高人指点。怎么弄更好的验证方法

解决方案 »

  1.   

    从TextBox继承一个。
    class MyTextBox : TextBox
    {
        public override string Text
        {
            get { return FormatStr(base.Text); }
            set { bast.Text = value; }
        }
    }
      

  2.   

    我的意思是TextBox继承一个类,
    protected void Button1_Click(object sender, EventArgs e)
        {
            this.lbText.Text= validate.FormatStr(this.TextBox1.Text);
            this.TextBox2.Text = this.TextBox1.Text;        //直接这样就行了,让TextBox直接继承一个验证类,不用像上边引用validate.Formatstr(),这样的效果可以实现吗?
        }
      

  3.   

    你用MyTextBox代替TextBox就可以了。
      

  4.   

    不用继承,只需要这样:TextBox1.TextChanged += new System.EventHandler(txt_Changed);然后在 txt_Changed 里 formatStr
      

  5.   

    可以用扩展方法实现,扩展方法:
    public static class Mytext
    {
        public static string CustomString(this TextBox B)
        {
            return  = Regex.Replace(B.Text, "[`~!@#$^&*()=|{}_':;',’#*\\[\\].<>/?~!@#¥……&*()—|{}【】‘;:”“'。,、?]", " ");
        }
    }
    调用方法:
    string returnstring=TextBox.CustomString();
    returnstring 就是替换的字符串