😎 Discover cool tips and tricks for customization in our next Developer Deep Dive virtual event - sign up now!

Issue with using a validation function for trailing/leading whitespaces in Sanity.io

9 replies
Last updated: Oct 20, 2021
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).

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,
      }
   )
}),
Can anyone point me in the right direction?
Oct 20, 2021, 3:26 PM
Under which field are you placing this rule? it looks like
blocks
might not be an array
Oct 20, 2021, 3:52 PM
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
Under which field are you placing this rule? it looks like
blocks
might not be an array
Oct 20, 2021, 3:52 PM
ah, the rule you’re using only applies to portable text fields, for a field of type string it’d be something like this:

validation: Rule => Rule.custom(name => {
  if (name.startsWith(' ') || name.endsWidth(' ')) {
    return 'No trailing space'
  }
  return true
})
something like that
Oct 20, 2021, 4:00 PM
check out the 2nd example in this section https://www.sanity.io/docs/validation#091e10f957aa
Oct 20, 2021, 4:01 PM
oh, okay, so I should also add
    if (typeof name === 'undefined') {
      return false
    }
meaning that it will not allow the value ‘undefined’, right?
Oct 20, 2021, 4:05 PM
yeah I think so!
Oct 20, 2021, 4:10 PM
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
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.

Was this answer helpful?