Reputation: 746
I tried to joiful validation using mongodb objectId.but its throwing error Property 'ObjectId' does not exist on type 'typeof import("/home/lenovo/Music/basic/node_modules/joiful/index")'
import * as jf from "joiful";
import {ObjectId} from 'mongodb';
class SignUp {
@jf.string().required()
username?: string;
@jf
.string()
.required()
.min(8)
password?: string;
@jf.date()
dateOfBirth?: Date;
@jf.boolean().required()
subscribedToNewsletter?: boolean;
@jf.ObjectId().required()
id?:ObjectId;
}
const signUp = new SignUp();
signUp.username = "rick.sanchez";
signUp.password = "wubbalubbadubdub";
const { error } = jf.validate(signUp);
Is it possible to validate objectId using joiful.
Upvotes: 3
Views: 311
Reputation: 701
I know that this question is along time ago, and the library maintainers didn't add this validator yet, for that I created a custom decorator that uses joiful
custom method to make custom validation
import * as jf from 'joiful';
import Joi from 'joi';
import { ObjectId } from 'mongodb';
export const objectIdValidationDecorator = () => jf.any().custom(({ schema }: { schema: Joi.Schema }) => {
return schema.custom((value, helpers) => {
const objectId = new ObjectId(value);
if (objectId.equals(value)) {
return objectId;
} else {
return helpers.error('any.invalid');
}
});
})
Usage:
class MyObj {
@objectIdValidationDecorator().required()
referenceId:ObjectId
}
Upvotes: 1