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

default discord avatar
Payload-Bot11 months ago
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
    11 months ago

    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.cs11 months ago


    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
    11 months ago

    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.cs11 months ago

    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 help straight from the Payload team with an Enterprise License.