Skip to main content

Activities Validation Helpers

๐Ÿ“– Overviewโ€‹

Helper Path: internal/api/v1/activities/helper/helper.js

The Activities validation helpers provide custom Joi validation functions for common data types used in activity and task management. Core responsibilities include:

  • MongoDB ID Validation: Validate ObjectId format
  • Time Format Validation: Validate HH:MM:SS time strings
  • Date Validation: Validate date strings and objects

๐Ÿ”ง Validation Functionsโ€‹

validateMongoID(value, helpers)โ€‹

Purpose: Joi custom validation function for MongoDB ObjectId format

Parameters:

  • value (String) - Value to validate
  • helpers (Object) - Joi helpers object

Returns:

  • value - If valid ObjectId
  • helpers.error('any.invalid') - If invalid

Business Logic:

const mongoose = require('mongoose');

function validateMongoID(value, helpers) {
if (!mongoose.Types.ObjectId.isValid(value)) {
return helpers.error('any.invalid');
}
return value;
}

Usage in Joi Schema:

const Joi = require('joi');

const schema = Joi.object({
user_id: Joi.string().custom(validateMongoID, 'MongoDB ObjectId validation').required(),
account_id: Joi.string().custom(validateMongoID, 'MongoDB ObjectId validation').required(),
});

Valid Examples:

  • "507f1f77bcf86cd799439011"
  • "60c72b2f9b1d4e3a5c8b4567"

Invalid Examples:

  • "invalid-id" - Not hex format
  • "507f" - Too short (must be 24 chars)
  • "zzzzzzzzzzzzzzzzzzzzzzz" - Invalid hex characters

validateTime(value, helpers)โ€‹

Purpose: Joi custom validation function for HH:MM:SS time format

Parameters:

  • value (String) - Time string to validate
  • helpers (Object) - Joi helpers object

Returns:

  • value - If valid time format
  • helpers.error('any.invalid') - If invalid

Business Logic:

function validateTime(value, helpers) {
const timeRegex = /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/;

if (!timeRegex.test(value)) {
return helpers.error('any.invalid');
}
return value;
}

Usage in Joi Schema:

const schema = Joi.object({
start_time: Joi.string().custom(validateTime, 'Time validation').required(),
end_time: Joi.string().custom(validateTime, 'Time validation').required(),
});

Valid Examples:

  • "09:30:00" - Morning time
  • "14:45:30" - Afternoon time
  • "23:59:59" - End of day
  • "00:00:00" - Midnight

Invalid Examples:

  • "9:30:00" - Missing leading zero
  • "25:00:00" - Invalid hour (>23)
  • "14:60:00" - Invalid minute (>59)
  • "14:45" - Missing seconds

Key Rules:

  • Hours: 00-23 (24-hour format)
  • Minutes: 00-59
  • Seconds: 00-59
  • Format: Must include leading zeros

validateDate(value, helpers)โ€‹

Purpose: Joi custom validation function for date strings and Date objects

Parameters:

  • value (String|Date) - Date to validate
  • helpers (Object) - Joi helpers object

Returns:

  • value - If valid date
  • helpers.error('any.invalid') - If invalid

Business Logic:

const moment = require('moment');

function validateDate(value, helpers) {
if (!moment(value).isValid()) {
return helpers.error('any.invalid');
}
return value;
}

Usage in Joi Schema:

const schema = Joi.object({
due_date: Joi.alternatives()
.try(Joi.date(), Joi.string().custom(validateDate, 'Date validation'))
.required(),
completed_at: Joi.alternatives()
.try(Joi.date(), Joi.string().custom(validateDate, 'Date validation'))
.optional(),
});

Valid Examples:

  • "2024-01-15" - ISO date string
  • "2024-01-15T10:30:00Z" - ISO datetime
  • new Date() - Date object
  • "Jan 15, 2024" - Moment-parseable string

Invalid Examples:

  • "invalid-date" - Not a valid date format
  • "2024-13-01" - Invalid month
  • "2024-02-30" - Invalid day for February

Key Rules:

  • Uses moment.js for validation (supports many formats)
  • Accepts both Date objects and strings
  • Rejects invalid dates (e.g., Feb 30)

๐Ÿ”€ Integration with Joi Schemasโ€‹

Activity Schema Exampleโ€‹

const Joi = require('joi');
const { validateMongoID, validateTime, validateDate } = require('./helper/helper');

const createActivitySchema = Joi.object({
account_id: Joi.string().custom(validateMongoID, 'MongoDB ObjectId validation').required(),

user_id: Joi.string().custom(validateMongoID, 'MongoDB ObjectId validation').required(),

title: Joi.string().min(1).max(200).required(),

start_time: Joi.string().custom(validateTime, 'Time validation').required(),

end_time: Joi.string().custom(validateTime, 'Time validation').required(),

due_date: Joi.alternatives()
.try(Joi.date(), Joi.string().custom(validateDate, 'Date validation'))
.required(),
});

// Usage in route
router.post('/activities', validate(createActivitySchema), createActivity);

Task Schema Exampleโ€‹

const updateTaskSchema = Joi.object({
task_id: Joi.string().custom(validateMongoID, 'MongoDB ObjectId validation').required(),

completed_at: Joi.alternatives()
.try(Joi.date(), Joi.string().custom(validateDate, 'Date validation'))
.optional(),

reminder_time: Joi.string().custom(validateTime, 'Time validation').optional(),
});

๐Ÿงช Edge Cases & Error Messagesโ€‹

MongoDB ID Validationโ€‹

// Valid ObjectId
validateMongoID('507f1f77bcf86cd799439011', helpers);
// Returns: '507f1f77bcf86cd799439011'

// Invalid ObjectId
validateMongoID('invalid-id', helpers);
// Returns: helpers.error('any.invalid')
// Error message: '"field" is invalid'

Time Validationโ€‹

// Valid time
validateTime('14:30:00', helpers);
// Returns: '14:30:00'

// Invalid time (missing leading zero)
validateTime('9:30:00', helpers);
// Returns: helpers.error('any.invalid')
// Error message: '"field" is invalid'

// Invalid time (out of range)
validateTime('25:00:00', helpers);
// Returns: helpers.error('any.invalid')

Date Validationโ€‹

// Valid date
validateDate('2024-01-15', helpers);
// Returns: '2024-01-15'

// Invalid date
validateDate('invalid-date', helpers);
// Returns: helpers.error('any.invalid')
// Error message: '"field" is invalid'

// Invalid date (Feb 30)
validateDate('2024-02-30', helpers);
// Returns: helpers.error('any.invalid')

โš ๏ธ Important Notesโ€‹

  1. Error Messages: All validators return generic 'any.invalid' error. Consider using custom error messages for better UX:

    .custom(validateMongoID, 'MongoDB ObjectId validation')
    .messages({
    'any.invalid': 'Must be a valid MongoDB ObjectId',
    })
  2. Moment.js Dependency: Date validation requires moment.js. If migrating to newer date libraries, update validateDate().

  3. Time Format: Strictly enforces HH:MM:SS with leading zeros. Does not accept HH:MM or other formats.

  4. Date Flexibility: validateDate() accepts many date formats (ISO, US, etc.) thanks to moment.js. Be specific if you need a particular format.

  5. No Timezone Handling: Time validation checks format only, not timezone. Handle timezone logic separately.

  6. Reusability: These validators are generic and can be used across different modules (tasks, calendar events, reminders, etc.).

  7. Performance: Regex validation (time) is faster than moment parsing (date). MongoDB ObjectId validation is very fast.

  • Tasks Module (documentation unavailable) - Task management using these validators
๐Ÿ’ฌ

Documentation Assistant

Ask me anything about the docs

Hi! I'm your documentation assistant. Ask me anything about the docs!

I can help you with:
- Code examples
- Configuration details
- Troubleshooting
- Best practices

Try asking: How do I configure the API?
09:31 AM