Open manpreet-compro opened 3 months ago
Hi, first of all: I think this idea has potential in being implemented and used widely.
However this can be widely interpreted, hi.how.are.you.google.com is a valid domain, but should it be a valid hostname? Or should only google.com or example.com be valid.
Lets look at mozilla's definition on hostname:
https://hello.world.example.com/ -> url.hostname = hello.world.example.com
But should www
also be part of it?
@m10rten Thanks for following up.
I believe the value returned from URL.hostname
should be considered a valid hostname. It may or may not include www
, depending on the domain, Ref: https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname
const url1 = new URL(
"https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname"
);
console.log(url1.hostname); // developer.mozilla.org
const url2 = new URL("https://hello.world.example.com/");
console.log(url2.hostname); // hello.world.example.com
const url3 = new URL("https://www.google.com/");
console.log(url3.hostname); // www.google.com
I further spent some time checking the RFC specification (https://datatracker.ietf.org/doc/html/rfc3986#autoid-21), As per the specifications, a valid hostname could be
Thanks for clearing that up!
Maybe we can work with that, how do you see using it? And what would the result look like?
Or exact like a new URL().hostname
?
I think it should be used similarly to existing zod string validations, such as email or uuid.
So this will be z.string().hostname()
.
As for the implementation options:
I've submitted a PR to add support for the hostname method in z.string() for enhanced validation.
Issue: I am working on a use case where I need to validate hostname strings before passing them to a database. While Zod supports URL validation, I could not find any built-in support for validating hostnames specifically.
For example, I need to validate strings such as:
Current Workaround: Currently, I am using a regular expression to validate hostnames. However, having built-in support in Zod for hostname validation would be more efficient and reliable.
Request: I would like to request the addition of hostname validation support in Zod, this would be beneficial. If this request makes sense, I am willing to contribute to adding this feature to the library.