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
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.
amazing. I'm also leaving this here.
https://payloadcms.com/docs/fields/overview#validationfor 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?
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/componentsthank 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
Discord
online
Get help straight from the Payload team with an Enterprise License.