A
arktype•4d ago
francis

How can we describe a string with a length restriction?

e.g.:
type("5 < string.numeric < 7").describe("valid otp")
type("5 < string.numeric < 7").describe("valid otp")
gives the following error message: otp must be valid otp (was 3) I would expect the description to override the insertion of the current length. Is there a way to do this? Similarly, is there an easy way to remove the field name from the error, for use in inline form error display?
9 Replies
ssalbdivad
ssalbdivad•4d ago
No description
ssalbdivad
ssalbdivad•4d ago
const otp = type("string.numeric").narrow(
(s, ctx) =>
s.length === 6 || ctx.reject({ expected: "a valid otp", actual: "" })
)

otp("123").toString() //?

const obj = type({
otp: otp
})

const result = obj({ otp: "123" })

if (result instanceof type.errors) {
console.log(result.summary)
console.log(result[0].message)
// .problem on the individual error omits context from path
console.log(result[0].problem)
console.log(result[0].expected) //?
console.log(result[0].actual) //?
}
const otp = type("string.numeric").narrow(
(s, ctx) =>
s.length === 6 || ctx.reject({ expected: "a valid otp", actual: "" })
)

otp("123").toString() //?

const obj = type({
otp: otp
})

const result = obj({ otp: "123" })

if (result instanceof type.errors) {
console.log(result.summary)
console.log(result[0].message)
// .problem on the individual error omits context from path
console.log(result[0].problem)
console.log(result[0].expected) //?
console.log(result[0].actual) //?
}
ssalbdivad
ssalbdivad•4d ago
I do plan to implement https://github.com/arktypeio/arktype/issues/977 soon which it looks like you've seen that would let you pass actual inline without a narrow
GitHub
Allow other error config like expected, actual, problem and `...
This would allow more granular customization e.g. of a field like password to omit actual.
francis
francisOP•4d ago
ah, I just found that 🙂 thank you! this is helpful
ssalbdivad
ssalbdivad•4d ago
Also re: your initial expression you can also do string == 6 for exact length constraint I know it looks a little weird, but it makes more sense in the context of the other comparators 😛
francis
francisOP•4d ago
oh, I couldn't figure that out I tried string = 6 but that failed iirc, min and max are in the docs, but not exact length
ssalbdivad
ssalbdivad•4d ago
Yeah you're probably right I'll add that
francis
francisOP•4d ago
another quick docs note: https://arktype.io/docs/expressions has a broken link. "Narrow expressions allow you to add custom validation logic and error messages. You can read more about them in their intro section" has a link to an intro section that 404s
ssalbdivad
ssalbdivad•4d ago
Thanks for letting me know. I wish the build would fail on broken links I kind of expected it to

Did you find this page helpful?