drobison
drobison

Reputation: 908

Trim all user input strings in ASP.NET Web Forms

I am looking for a way to trim all user input in ASP.NET without calling Trim() on every string instance. I came across extending the DefaultModelBinder for MVC. Is there a way to do this in web forms? What options are available? As a less desirable option, is there a way to incorporate this into the set method of a class?

Upvotes: 3

Views: 3580

Answers (3)

Win
Win

Reputation: 62260

Here is the utility method to trim all TextBoxes in a page (or a parent control) recursively.

public static void TrimTextBoxesRecursive(Control root)
{
    foreach (Control control in root.Controls)
    {
        if (control is TextBox)
        {
            var textbox = control as TextBox;
            textbox.Text = textbox.Text.Trim();
        }
        else
        {
            TrimTextBoxesRecursive(control);
        }
    }
}

Usage

protected void Button1_Click(object sender, EventArgs e)
{
    TrimTextBoxesRecursive(Page);
}

Upvotes: 4

Gary Walker
Gary Walker

Reputation: 9134

You have to call this extension method from the appropriate parent, e.g. Page.TrimTextControls

public static void TrimTextControls(this Control parent, bool TrimLeading)
{
  foreach (TextBox txt in parent.GetAllControls().OfType<TextBox>())
  {
    if (TrimLeading)
    {
      txt.Text = txt.Text.Trim();
    }
    else
    {
      txt.Text = txt.Text.TrimEnd();
    }
  }
}

Upvotes: 1

David
David

Reputation: 218857

You could create a custom TextBox which always returns a trimmed version of the text:

public class CustomTextBox : TextBox
{
    public override string Text
    {
        get { return base.Text.Trim(); }
        set { base.Text = value; }
    }
}

Then just use this instead of the normal TextBox anywhere you need this behavior.

Upvotes: 8

Related Questions