Niar
Niar

Reputation: 540

Regex to exclude character

Hi I want to check in an ASP TextBox that user does not enter the following characters:

&'"<>

I have given a CustomValidator like

<asp:CustomValidator ID="cvtxtName" runat="server" OnServerValidate="SpecialCharactersFilter" ControlToValidate="txtName" ErrorMessage="Special characters not allowed" />

And c# code

protected void SpecialCharactersFilter(object sender, ServerValidateEventArgs e)
    {
        e.IsValid = !Regex.IsMatch(e.Value, @"");
    }

But I'm stuck at writing the regex.

Upvotes: 0

Views: 1030

Answers (3)

Pankaj Bodani
Pankaj Bodani

Reputation: 303

protected void SpecialCharactersFilter(object sender, ServerValidateEventArgs e)
{
    e.IsValid = !Regex.IsMatch(e.Value, @"[&'""<>]+");
}

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460038

Because you use a CustomValidator instead of a RegularExpressionValidator i will show you a non-regex solution:

e.IsValid = !e.Value.Intersect("&'\"<>").Any();

You need to add using System.Linq for the extension methods.

Upvotes: 1

Zohar Peled
Zohar Peled

Reputation: 82474

try this:

 e.IsValid = Regex.IsMatch(e.Value, "^[^&'\"<>]+$");

^ marks the beginning of the string

[^] means that any char inside the square brackets is not allowed

+ means one time or more (meaning that your input must be at least 1 character long to pass the IsMatch test)

$ marks the end of the string

Upvotes: 1

Related Questions