0

am trying to implement validations using regex

The validation in aspx page works fine

<asp:RegularExpressionValidator ID="regexEmailValid" display="none" runat="server" ValidationExpression="(([a-z]|[A-Z]|[0-9]|[ ]|[-]|[_]|[@]|[.]|[!]|[$])*)*" ControlToValidate="txtUser" ErrorMessage="Invalid User Name Format"></asp:RegularExpressionValidator>

same one in code behind always returns true

Regex.IsMatch(UserName, "(([a-z]|[A-Z]|[0-9]|[ ]|[-]|[_]|[@]|[.]|[!]|[$])*)*")

tried adding ^ to start but still it always returns true

Regex.IsMatch(UserName, "^(([a-z]|[A-Z]|[0-9]|[ ]|[-]|[_]|[@]|[.]|[!]|[$])*)*")

What am i doing wrong ?

4
  • 1
    On what input string? * means zero too so this always match. Commented May 10, 2018 at 20:02
  • using test%= also returns true Commented May 10, 2018 at 20:03
  • It seems you need this ^[a-zA-Z0-9 _@.!$-]+$ Commented May 10, 2018 at 20:04
  • @revo thank you will try this am not so good at regex : ) i think i missed the $ for end of string..but your looks short and sweet :) Commented May 10, 2018 at 20:08

1 Answer 1

1

You are misusing alternations and capturing groups while you could have all those character classes into one. You also have * as quantifier which means zero or more. So regardless of anchors it matches. Your solution would be:

^[a-zA-Z0-9 _@.!$-]+$
Sign up to request clarification or add additional context in comments.

4 Comments

can these include character in any order in case i need to add remove in feature ?
Order doesn't matter. But some special characters like - and ^ should be escaped or treated carefully.
i noticed - at the end...what should i change if i should allow ^ in to my current regex ?
^ has a special meaning when is used as first char in a character class. So avoid using it there if you mean a literal ^. A safe way would be escaping. With escaping \^ it doesn't matter where it resides.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.