Bob Tway
Bob Tway

Reputation: 9603

Regular Expression Validator to catch non-alphanumeric characters

This is a really dense question, but I'm tired.

I need a regular expression that can do in a validator control that will catch any non-alphanumeric characters. In other words the regexp needs to match if the string contains only a-z, A-Z or 0-9.

I'm aware that it's quite easy to write a regular expression that will match if there's an illegal character in a string - the trouble is that I need the opposite of this because it's in a validator. Thats' what's giving me a headache.

Solutions appreciated.r

Upvotes: 1

Views: 6903

Answers (4)

thejh
thejh

Reputation: 45568

Try

^[a-zA-Z0-9]*$

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 284816

Use:

^[a-zA-Z0-9]*$

Upvotes: 0

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74380

If empty string is not valid:

^[[:alnum:]]+$

Upvotes: 0

Ahmad Mageed
Ahmad Mageed

Reputation: 96487

Your set of acceptable characters are [a-zA-Z0-9]. You want to validate on anything that doesn't match those, so use a ^ to negate this character class:

[^a-zA-Z0-9]+

In addition, make sure you use a RequiredFieldValidator along with your RegularExpressionValidator since the latter doesn't catch blank entries. Per MSDN:

If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to prevent the user from skipping an input control.

Upvotes: 5

Related Questions