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.

Hello team, I have two fields one called startTime...

default discord avatar
Payload-Botlast year
4

Hello team, I have two fields one called startTime and the other called endTime. I would like to have a custom validation to check if these two fields time check up. No startTime greater than endTime can be submitted through APIs or Admin panel. Please guide me



Original message from @alnasser.cs - Moved from https://discord.com/channels/967097582721572934/967097582721572937/1141457672433061898 (in #general)
  • discord user avatar
    tylandavis
    last year

    Hey @alnasser.cs, you can do this by adding a custom

    validate

    function to your endTime field:


    {
      name: 'endTime',
      type: 'date',
      validate: (value, { data }) => {
        if (value <= data.startTime) {
          return "End time must be after start time";
        }
      }
    }


    this will check that

    endTime

    is greater than

    startTime

    , and return the error message if not.

  • default discord avatar
    alnasser.cslast year


    amazing. I'm also leaving this here.

    https://payloadcms.com/docs/fields/overview#validation

    for whoever coming to read this



    one more question, is it possible to check validation on effect. like as soon as the user pick a a date. I would like to check if it's correct before they go and click save?

  • discord user avatar
    tylandavis
    last year

    Out of the box, I don't believe so. You could achieve this by adding in your own custom component, but that is more advanced.



    More on custom components here:

    https://payloadcms.com/docs/admin/components
  • default discord avatar
    alnasser.cslast year

    thank you. Maybe it's something I can help with when I figure out the framework



    validate: (value, { data, operation }) => {


    // if(operation == 'create' || operation !== 'update') {


    // console.log('operation not include ' + operation)


    // return true;


    // }


    data.timeSlots.forEach((timeSlot, i) => {


    console.log(timeSlot)


    if (new Date(timeSlot.endTime) <= new Date(timeSlot.startTime)) {


    console.log('through error')


    return

    Issue at Time Slot ${i+1}. End time must be after start time

    ;


    }


    });


    return true;


    },



    I wrote the validation function as described. I hit the if condition but return don't don't through error and the framework goes ahead and save it.



    error figured out. the return is inside the array.forEach() -.-

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..