I see the Nginx HttpRewriteModule documentation has an example to rewrite a www-prefixed domain to a non-www-prefixed domain:
if ($host ~* www\\.(.*)) { set $h
if ($host ~* ^[^.]+\.[^.]+$) { rewrite ^(.*)$ http://www.$host$1 permanent; }
It's only possible to get valid hostnames because the request will never make it to your server otherwise, so there's no need to build your own validation logic.