user123456789
user123456789

Reputation: 2004

check string for invalid characters

I have a textbox called Comment in a form. After the user enters their comment and click on the save button I want to search through this comment string for any invalid character such as full stops, commas, brackets etc. If the string contains any of these character then I want to throw an exception.

I know in javascript you can use RegularExpressionValidator and check the validation with ValidationExpression="^[a-zA-Z0-9]*$" but how can you do it in the code behind?

Right now I just check if the comment has been left empty but how do I check if the comment contains anything other than numbers and letters?

if (string.IsNullOrEmpty(txtComment.Text))
{
    throw new Exception("You must enter a comment");
}

Upvotes: 1

Views: 7121

Answers (2)

IrishChieftain
IrishChieftain

Reputation: 15253

// Basic Regex pattern that only allows numbers, 
// lower & upper alpha, underscore and space
static public string pattern = "[^0-9a-zA-Z_ ]";

static public string Sanitize(string input, string pattern, string replace)
{
    if (input == null)
    {
        return null;
    }
    else
    {
        //Create a regular expression object
        Regex rx;
        rx = new Regex(pattern);
        // Use the replace function of Regex to sanitize the input string. 
        // Replace our matches with the replacement string, as the matching
        // characters will be the ones we don't want in the input string.
        return rx.Replace(input, replace);
    }
}

Upvotes: 1

techspider
techspider

Reputation: 3410

It is same logic using Regex

Regex regex = new Regex(@"^[a-zA-Z0-9]*$");
Match match = regex.Match(txtComment.Text);
if (!match.Success)
{
    throw new Exception("You must enter a valid comment");
}

Upvotes: 4

Related Questions