How to validate Azure Container name using regex? I found the following line of code from some other post, but it is not validating the consecutive dashes (-).
if (!Regex.IsMatch(containerName, @"^[a-z0-9](([a-z0-9\-[^\-])){1,61}[a-z0-9]$"))
throw new Exception("Invalid container name);
E.g. the following string is considered valid with the above regex pattern:
test--test
The rules are:
-
);-
) Must Be Immediately Preceded and Followed by a Letter or NumberI know it's not exactly what you asked, but rather than rolling your own regex, you can use a method that is built into the storage client library: Microsoft.Azure.Storage.NameValidator.ValidateContainerName(myContainerName)
If the name is not valid then this method throws an ArgumentException
. As you would guess from the name, this static class contains methods for validating names of queues, tables, blobs, directories and others.
If you follow your custom way of solving the issue, you can use
^[a-z0-9](?!.*--)[a-z0-9-]{1,61}[a-z0-9]$
See regex demo
The (?!.*--)
lookahead will fail a match if there are 2 consecutive hyphens in the string.
Now, speaking about the Microsoft.WindowsAzure.Storage.NameValidator.ValidateContainerName(string containerName)
: the code is just repeating the logic of the regex above with separate argument exceptions per issue.
private const int ContainerShareQueueTableMinLength = 3;
private const int ContainerShareQueueTableMaxLength = 63;
These two lines set the min and max length of the container name and are checked against in the private static void ValidateShareContainerQueueHelper(string resourceName, string resourceType)
method. The regex used there is
private static readonly Regex ShareContainerQueueRegex =
new Regex("^[a-z0-9]+(-[a-z0-9]+)*$", NameValidator.RegexOptions);
So, this pattern is all you need if you add the length restriction to it:
^(?=.{3,63}$)[a-z0-9]+(-[a-z0-9]+)*$
^^^^^^^^^^^^
This regex is a "synonym" of the one at the top of the answer.
You should use the NameValidator
approach if you need different ArgumentException
s to signal different issues. Else, you may use your one-regex solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With