Click here to Skip to main content
15,037,388 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Please can someone write me a code for checking whether an entered string contains invalid characters like (<,>,&,%,",\,/,?,*,|)
If the string contains the above mentioned characters then it should pop –up a message “Please enter valid string”. Or else it should return true.
Please I want this code using Regular expression in C#.
Updated 29-Aug-11 5:25am
Uday P.Singh 29-Aug-11 7:31am
what you have tried?

Why drag in all the overhead involved in a regular expression when a simpler method is available? Put this extension method in your code, and you can then iuse it on any string with any invalid character set:

public static class ExtendStrings
    public static bool ContainsAny(this string value, string data)
        bool result = false;
        foreach(char c in data)
            if (value.Contains(c)
                result = true;
        return result;

Usage would be:

if (!myString.ContainsAny("(<,>,&,%,\",\\,/,?,*,|)"))
    // string is valid, do something appropriate

Simon Bang Terkildsen 29-Aug-11 13:45pm
Completely agree if you don't need pattern matching don't use regex.
Kim Togo 29-Aug-11 14:24pm
And yes. Why make it more complex, when the answer is very simple.
Another point of view:

If you are working in WinForms, you have a 'MaskedTextBox' control that will take care of this very simply: the control has been there since .NET 2.0.

And, it is generally better design, to make 'illegal' characters in a text-entry field to be impossible to enter, in the first place.

Note that the MaskedTextBox does not support multi-lines, and does not raise the AcceptsTabChanged Event.
Use this expression

<asp:RegularExpressionValidator Display="Dynamic" ID="regvalCheckValidSearchString"
                       CssClass="alert" ControlToValidate="txtQueryName" runat="server" ErrorMessage=""></asp:RegularExpressionValidator>

In CS file add

public const string REGULAREXPRESSION_BLACKLIST_CHARACTERS = "[^\\=\\<\\>\\,\\(\\)\\+\\[\\];\\?\\*\\$%\\^&/\\\\|]*";

regvalCheckValidSearchString.ValidationExpression = AppConstants.REGULAREXPRESSION_BLACKLIST_CHARACTERS;
Simon Bang Terkildsen 29-Aug-11 13:44pm
Just a suggestion, when writing a regex you might want to use a literal string e.g. @"\ not escaped, not necesrry" as it's must easier to read.
Anuja Pawar Indore 30-Aug-11 2:38am
Right agree. Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900