Creating a String Validation and Sanitization Function in C#: A Step-by-Step Guide

aamasum
3 min readNov 12, 2024

--

Introduction

In C# applications, especially when dealing with databases, it’s common to need a function that validates, sanitizes, and truncates strings based on specific criteria. For example, if you’re dealing with user inputs, these inputs often need to be cleaned to avoid issues such as SQL injection or over-length errors. This article will walk you through creating a robust function to handle these cases in a simple and efficient way.

Let’s dive into a function we call RetValidLen. This function takes a string and a maximum length, then:

  • Removes extra spaces,
  • Replaces problematic characters (like single quotes), and
  • Truncates the string if it exceeds the specified length.

Step-by-Step Explanation of the RetValidLen Function

Here’s the code we’ll be working with:

public object RetValidLen(string str, int maxLength)

{

// Check if the input string is empty or whitespace

if (string.IsNullOrWhiteSpace(str))

{

return DBNull.Value;

}

// Trim the string and replace single quotes with spaces

string sanitizedStr = str.Trim().Replace(“‘“, “ “);

// Return a substring if it exceeds the specified maximum length

if (sanitizedStr.Length > maxLength)

{

return sanitizedStr.Substring(0, maxLength); // Starting from 0 to get the full substring

}

return sanitizedStr; // Return the sanitized string as is if it’s within the length limit

}

Let’s break down how this code works, step-by-step.

1. Checking for Empty Strings

The function starts by checking if the str parameter is empty or consists only of whitespace. This is important because empty strings are often treated differently in database operations. For instance, some applications prefer DBNull.Value for empty fields, so we use DBNull.Value for any string input that is either empty or whitespace-only.

if (string.IsNullOrWhiteSpace(str))

{

return DBNull.Value;

}

2. Sanitizing the String

Next, we sanitize the string. This involves:

  • Trimming whitespace from both ends using Trim() to ensure a clean start and end.
  • Replacing single quotes (‘) with spaces, which can help prevent SQL injection vulnerabilities in cases where the string is used in database queries.

string sanitizedStr = str.Trim().Replace(“‘“, “ “);

3. Truncating the String

The final step is to check if the sanitized string exceeds the specified maxLength. If it does, we use Substring(0, maxLength) to limit the string to the maximum length.

if (sanitizedStr.Length > maxLength)

{

return sanitizedStr.Substring(0, maxLength);

}

Otherwise, we simply return the sanitized string as is.

Example Scenarios

To illustrate how this function works, let’s go through a few example cases.

Example 1: Standard String Within Length Limit

string example1 = “Hello, World!”;

Console.WriteLine(RetValidLen(example1, 15)); // Output: “Hello, World!”

Since “Hello, World!” is under the 15-character limit, the function returns it unmodified.

Example 2: String Exceeding Length Limit

string example2 = “This is a very long string that exceeds the limit.”;

Console.WriteLine(RetValidLen(example2, 10)); // Output: “This is a “

The string exceeds the 10-character limit, so the function returns only the first 10 characters: “This is a “.

Example 3: String with Single Quotes

string example3 = “It’s a test!”;

Console.WriteLine(RetValidLen(example3, 20)); // Output: “It s a test!”

Here, the single quote (‘) is replaced with a space, resulting in “It s a test!”.

Example 4: Empty String

string example4 = “”;

Console.WriteLine(RetValidLen(example4, 10)); // Output: DBNull.Value

An empty string is returned as DBNull.Value, aligning with database null handling.

Example 5: String with Only Whitespace

string example5 = “ “;

Console.WriteLine(RetValidLen(example5, 5)); // Output: DBNull.Value

Since the input is all whitespace, DBNull.Value is returned.

Why Use RetValidLen?

This function is especially useful in applications with database interactions. Here are a few key benefits:

  • Sanitization: By replacing single quotes, it helps avoid SQL injection or syntax issues.
  • Length Control: It ensures that strings don’t exceed set length limits, preventing database errors.
  • Database Compatibility: Treating empty strings as DBNull allows better compatibility with database fields that don’t accept empty strings but accept null values.

Conclusion

Creating a function like RetValidLen is a practical way to handle user input in C# applications that interact with databases. By checking for empty values, replacing problematic characters, and controlling string length, you can ensure your data is clean, safe, and ready for storage or further processing.

--

--

aamasum
aamasum

Written by aamasum

0 Followers

Net Core | C# | SQL

No responses yet