Validation on field not working as expected

default discord avatar
hellboy124124
3 months ago
4

Hello,


I am currently experiencing some rather unexpected behaviour, where it only works every third time. If I click the Save button X times in a row, it only works every third time.



Code:



// ProductExternalReviews.ts
import { CollectionConfig } from 'payload/types';

import { validateYoutubeUrl } from '../utilities/helpers';
import Products from './Products';

const ProductExternalReviews: CollectionConfig = {
  slug: 'product-external-reviews',
  access: {
    read: () => true,
  },
  versions: true,
  fields: [
    // Main
    {
      name: 'product',
      type: 'relationship',
      required: true,
      relationTo: Products.slug,
      index: true,
      admin: {
        description: 'In case it is a bundle, select the main product',
      },
    },
    {
      name: 'type',
      type: 'select',
      required: true,
      defaultValue: 'youtube-video-url',
      options: [{ label: 'Youtube Video URL', value: 'youtube-video-url' }],
    },
    {
      name: 'youtubeVideoUrl',
      type: 'text',
      required: true,
      admin: {
        condition: (_, siblingData) => siblingData?.type === 'youtube-video-url',
      },
      validate: validateYoutubeUrl,
    },
  ],
};

export default ProductExternalReviews;

// helpers.ts
const youtubeUrlRegex = /^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$/g;
export const validateYoutubeUrl = (value: string) => {
  if (!youtubeUrlRegex.test(value)) {
    return 'Invalid Youtube URL';
  }

  return true;
};


What am I doing wrong here?

  • default discord avatar
    notchr
    3 months ago

    Hmm, it seems unlikely that it's only saving every third time - are you able to check your dev tools log for errors? Can you narrow down the issue to possibly the regex pattern or something else?



    For instance, make the regex super basic, or remove it even, just to rule out other possibilities

  • default discord avatar
    hellboy124124
    3 months ago

    Well, this is a really strange one. I fixed it by putting the youtubeUrlRegex variable inside the validateYoutubeUrl function. Not really sure why that fixed it, because I did validate the the correct regex is always passed when testing, but strange stuff!

  • default discord avatar
    jarrod69420
    3 months ago

    That is funky, but interesting! Glad you were able to solve 👍

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.