Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Validation on field not working as expected

default discord avatar
bobalazek2 years ago
3

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
    notchr2 years 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
    bobalazek2 years 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!

  • discord user avatar
    jarrod_not_jared
    2 years ago

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

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.