Reputation: 5109
I use following Regex to validate a string ^[a-zA-Z0-9-/]*
private static void ValidateActualValue(string value)
{
if (String.IsNullOrEmpty(value)) throw new ArgumentNullException("value");
if (Regex.IsMatch(value, (@"^[a-zA-Z0-9-/]*")))
{
throw new InvalidBarcodeException(value);
}
}
The following string should be allowed string correctBarcodeString = "1-234567890/A"; However there's still an exception thrown.
Allowed values should be:
Upvotes: 3
Views: 137
Reputation: 92996
Inside a character group the -
has to be at the beginning or at the end, otherwise it has to be escaped.
So change it to
"^[a-zA-Z0-9/-]*"
Edit:
I would also suggest an anchor at the end of the regex, otherwise it will also match as long as the first part is valid.
"^[a-zA-Z0-9/-]*$"
if you want to avoid matching the empty string then use +
instead of *
. Or if you know a valid Min/Max Range for the length use {4,20}
, if the minimum amount of characters is 4 and the maximum is 20.
Upvotes: 1
Reputation: 91428
Put the -
character at the end of the class or escape it.
[a-zA-Z0-9/-]
or [a-zA-Z0-9\-/]
Upvotes: 2
Reputation: 1941
I that that you really want;
@"^[\w/-]+"
Using a + instead of a * will also cover the empty string. \w = all numbers + letters
Upvotes: 1
Reputation: 81660
Change
@"^[a-zA-Z0-9-/]*"
to
@"^[a-zA-Z0-9/]*"
You have an extra hyphen after 9.
Upvotes: 0