0 day streak
csharp / intermediate
Snippet

Validating Input Integrity with Regular Expressions

Input validation is a core pillar of security. Using Regex allows you to enforce strict formats. Providing a timeout to Regex.IsMatch prevents potential Denial of Service (DoS) attacks via backtracking (ReDoS).

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
using System.Text.RegularExpressions;
public class SecurityValidator {
public bool IsValidUsername(string input) {
if (string.IsNullOrWhiteSpace(input)) return false;
// Only alphanumeric, 5-15 characters
string pattern = @"^[a-zA-Z0-9]{5,15}$";
return Regex.IsMatch(input, pattern, RegexOptions.None, System.TimeSpan.FromMilliseconds(100));
}
}
Breakdown
1
@"^[a-zA-Z0-9]{5,15}$"
A verbatim string literal defining a pattern for 5 to 15 alphanumeric characters.
2
System.TimeSpan.FromMilliseconds(100)
Safety timeout to prevent catastrophic backtracking during regex evaluation.