katit
katit

Reputation: 17915

How do I make sure string does not contain colon using regex?

I'm writing validation regex in c# - basically need to ensure that property does not have ":" in it. I'm total newbee with regex. This is what I have and it doesn't seem to work.. I read beginners FAQ on regex and this is what I came up with "[^:]"

[StringLengthVerifier(MaxValue = 25, IsRequired = true, ErrorMessageResourceName = "MEMUser_UserName")]
        [RegexVerifier("User Name", @"[^:]", ErrorMessage = "User name cannot contain colons")]
        public string UserName { get; set; }

Upvotes: 0

Views: 5288

Answers (2)

Regexident
Regexident

Reputation: 29552

By enclosing the character class with the string/line boundary meta characters:

^[^:]*$

and using the right regex mode for making them match the beginning/end of string.

Or by using

\A[^:]*\Z

(assuming C# regex support them).

Upvotes: 3

Adam Mihalcin
Adam Mihalcin

Reputation: 14468

Don't use a regular expression. Since you only want to check for the presence of the colon character, simply ensure that

UserName.Contains(":")

evaluates to false. See MSDN for an explanation of String.Contains.

Upvotes: 1

Related Questions