Trimming Whitespace From Text Inputs In ASP.NET WebForms – The Easy Way

by Oliver 22. September 2016 01:02

When I validate forms, I usually don't want the user to allow to enter only whitespace in any of the text fields that I deem required. With a handful of them, checking for that condition can be annoying.

Let me introduce you to… TrimTextBox!

To centralize the concern to trim padding whitespace from text inputs, I simply derived from the built-in TextBox class and overrode a single property – Text:

With this simple piece of code my backend validation logic can now focus on the business rules, e.g. a minimum length of one character, without having to worry about leading, trailing, or only whitespace in any input field.

Don't Repeat Yourself – Keep it DRY

Whenever I encounter a piece of code that repeats more than once, I try and refactor that code away to make it reusable and sometimes even to completely hide a certain aspect of it from the current context so that when reading a block of code I can decide whether I want to dive deeper into the nitty gritty details or just get an overview of the workflow I'm looking at. This saves my brain some precious resources ;-)

I wonder what other use cases you can come up with where a specialized control can make your developer life simpler :-)

Happy coding (subclassing)!

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for jQuery. Enjoy MVC 4 and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our daughter. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.