Issue with using a validation function for trailing/leading whitespaces in Sanity.io
9 replies
Last updated: Oct 20, 2021
C
Hello, I am trying to use this (https://github.com/coreyward/sanity-pills/blob/master/src/lib/blockValidator.js ) validation function for no trailing/leading whitespaces, but I get this error in sanity (screenshot).
Can anyone point me in the right direction?
validation: (Rule) => Rule.required().custom((blocks) => { const offendingPaths = (blocks || []) .filter(({ _type, children }) => { if (_type !== "block") return false; const { 0: first, length, [length - 1]: last } = children || []; return first?.text.startsWith(" ") || last?.text.endsWith(" ") }) .map((block, index) => [{ _key: block._key }] || [index]); return ( offendingPaths.length === 0 || { message: "Blocks cannot start or end with whitespace", paths: offendingPaths, } ) }),
Oct 20, 2021, 3:26 PM
D
Under which field are you placing this rule? it looks like
blocksmight not be an array
Oct 20, 2021, 3:52 PM
C
adding a bit more code:
export default { name: "instructor", title: "Instructor", type: "document", fields: [ { name: "name", title: "Name", type: "string", validation: << rule is here >>, }, { name: "bio", title: "Bio", type: "text", },... ]}
Oct 20, 2021, 3:56 PM
D
Under which field are you placing this rule? it looks like
blocksmight not be an array
Oct 20, 2021, 3:52 PM
D
ah, the rule you’re using only applies to portable text fields, for a field of type string it’d be something like this:
something like that
validation: Rule => Rule.custom(name => { if (name.startsWith(' ') || name.endsWidth(' ')) { return 'No trailing space' } return true })
Oct 20, 2021, 4:00 PM
D
check out the 2nd example in this section https://www.sanity.io/docs/validation#091e10f957aa
Oct 20, 2021, 4:01 PM
C
oh, okay, so I should also add
meaning that it will not allow the value ‘undefined’, right?
if (typeof name === 'undefined') { return false }
Oct 20, 2021, 4:05 PM
D
yeah I think so!
Oct 20, 2021, 4:10 PM
C
ooh it makes sense, becausee if we got to the namee.startsWith part, it would crash, so we have to check for them before that
Oct 20, 2021, 4:13 PM
C
took me a bit, thank you
Oct 20, 2021, 4:13 PM
Sanity– build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.