Azure Container Name RegEx
In Powershell, you can do this:
function Test-ContainerNameValidity($ContainerName)
{
Import-Module -Name AzureRM
Write-Host "Testing container name against Microsoft's naming rules."
try {
[Microsoft.WindowsAzure.Storage.NameValidator]::ValidateContainerName($ContainerName)
Write-Host -ForegroundColor Green "Container name is valid!"
return
}
catch {
Write-Host -ForegroundColor Red "Invalid container name. Please check the container name rules: https://learn.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata#container-names"
Write-Host -ForegroundColor Red "The script is now exiting."
exit
}
}
I 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.