[00:01] At some point you might need to customize the validation logic entirely, especially when it comes to primitive values. Here we've got a handful of room number examples. Some of them are valid while others are invalid. The pattern for a proper room number is that the first character is an uppercase letter such as a here And then it's followed by three digits like here a 101 other examples are invalid so in order to create a custom Zod schema we need to run z.custom and pass a callback. And the callback is going to accept what is the value that is going to be validated.
[00:42] And it's expected to return a Boolean value or a value that is going to be automatically coerced to Boolean. True means that it's valid. Now, in case of our room type, we would like to provide some type safety. And unfortunately, Zod's custom schema doesn't support type inference. So as we can see, even though that I have typed room type of type string, it's not getting inferred correctly.
[01:10] So what we need to do actually is to put the type parameter over here explicitly. And unfortunately, this doesn't work the other way around so still room type is of type Any. So what we might need to do is first to check whether the type of room type is string but we're just going to limit ourselves to using the room number pattern again. First is the character and then followed by three digits. So what we're going to do is to run the test method on whatever is the room type over here.
[01:47] If it's true and test returns a boolean value. If it's true then it's valid, if it's not then it's invalid. Now as the second parameter we might want to pass the validation message if the validation fails so that would be room number must be in format blah blah blah so now let's run this file against ts-node and we would see what's going on so as For the first three they are correct so parse itself is going to return whatever was passed here and we can see that they are correct and here we get an error saying that a room number must be in format blah blah blah our custom message. So whenever you need z.custom remember that you need to take extra care about type safety.