Source: Top Shelf It Solutions Blog

Top Shelf It Solutions Blog Truncating user input before storing it in a database column with the fixed length

It is considered best practice to validate user input both client-side and server-side. HTML itself allows you to specify maxlength property on the input tags to prevent a user from overflowing desired input filed value:<input type="text" name="firstName" maxlength="50" />The ASP.NET TextBox control has the following syntaxis for it:<asp:TextBox runat="server" ID="txtUserInput" MaxLength="50" />It works fine with single-line text boxes, but if you are using a multi-line text box (<textarea />), the property doesn't work anymore. It is up to the developer to implement maxlength validation for the text areas. You can write a piece of javascript code which counts the number of typed elements in a text area and decrements the counter on-the-fly providing instant feedback to the user of how many more allowed characters they have left to type. But if the user has their javascript disabled or if you are getting input from some external source (i.e. user-agent string of a browser), then you should truncate user input yourself before storing it in the database with the fixed column width.An easy way to do it in C# is to use the Substring function in conjunction with Math.Min function:string truncatedValue = txtUserInput.Text.Length > 0 ? txtUserInput.Text.Substring(0, Math.Min(50, txtUserInput.Text.Length) - 1) : String.Empty;Math.Min will return the minimum of 2 values and Substring will override the txtUserInput.Text value with truncated version if user input is longer than the allowed value of 50 characters.

Read full article »
Est. Annual Revenue
$100K-5.0M
Est. Employees
25-100
CEO Avatar

CEO

Update CEO

CEO Approval Rating

- -/100