84 words, 1 min read

If you ever need to validate if a string can be used as an Amazon S3 bucket, you can do it with a regular expression.

TypeScript

const isValidS3BucketName = (bucketName: string): boolean => {
if (!bucketName || bucketName === '') {
return false;
}
const vatNumberRegex = new RegExp(
/^(?!xn--|sthree-|amzn-s3-demo-|.*-s3alias$|.*--ol-s3$|.*--x-s3$)[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,
);
return vatNumberRegex.test(bucketName);
};

PHP

function isValidS3BucketName(string $bucketName): bool {
if (empty($bucketName)) {
return false;
}
$vatNumberRegex = '^(?!xn--|sthree-|amzn-s3-demo-|.*-s3alias$|.*--ol-s3$|.*--x-s3$)[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/';
return preg_match($vatNumberRegex, $bucketName) === 1;
}

The rules for the names can be found here.