<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Habil M on Medium]]></title>
        <description><![CDATA[Stories by Habil M on Medium]]></description>
        <link>https://medium.com/@habilm?source=rss-80ceb7ad7e19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RghJyyvgSWd1P9LpAQVF2w.jpeg</url>
            <title>Stories by Habil M on Medium</title>
            <link>https://medium.com/@habilm?source=rss-80ceb7ad7e19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:26:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@habilm/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to create a custom validation in Class validator to check that a given value is unique in…]]></title>
            <link>https://medium.com/@habilm/how-to-create-a-custom-validation-in-class-validator-to-check-that-a-given-value-is-unique-in-e660fcfd1b49?source=rss-80ceb7ad7e19------2</link>
            <guid isPermaLink="false">https://medium.com/p/e660fcfd1b49</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[class-validator]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Habil M]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 13:59:08 GMT</pubDate>
            <atom:updated>2024-09-12T13:59:08.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to create a custom validation in Class validator to check that a given value is unique in MongoDB</h3><h3>Objective</h3><p>Today I want to show you how to create a custom validation <strong>decorator </strong>to check that the given value is unique in the collection(or MongoDB table) for any field like email, username or anything, with <strong>Class-Validaor</strong> in a <strong>NestJS </strong>application.</p><h3>What is a Class Validator?</h3><p>class-validator allows the use of decorator and non-decorator-based validation. Internally uses validator.js to perform validation. class-validator works on both browser and node.js platforms. see more at <a href="https://www.npmjs.com/package/class-validator">https://www.npmjs.com/package/class-validator</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRUYJiyL1bu8rcsbUSkjrQ.png" /></figure><h3>How to do it?</h3><p>It&#39;s just simple like following</p><pre>//IsUnique.decorator.ts<br>import { InjectModel } from &#39;@nestjs/mongoose&#39;;<br>import {<br>  registerDecorator,<br>  ValidationArguments,<br>  ValidationOptions,<br>  ValidatorConstraintInterface,<br>} from &#39;class-validator&#39;;<br>import { Model } from &#39;mongoose&#39;;<br>import { User } from &#39;src/modules/users/schemas/user.schema&#39;;<br><br>@ValidatorConstraint({ name: &#39;UniqueValue&#39;, async: true })<br>@Injectable()<br>export class UniqueValue implements ValidatorConstraintInterface {<br>  constructor(@InjectModel(User.name) private readonly userModel: Model&lt;User&gt;) {}<br><br>  async validate(value: string, args: ValidationArguments): Promise&lt;boolean&gt; {<br>    const user = await this.userModel.findOne({ [args.property]: value });<br>    return !user; // Return true if the user is NOT found, meaning it&#39;s unique<br>  }<br><br>  defaultMessage(args: ValidationArguments) {<br>    // Default error message<br>    return `${args.property} already exists`;<br>  }<br>}<br><br>export function IsUnique(validationOptions?: ValidationOptions) {<br>  return function (object: object, propertyName: string) {<br>    registerDecorator({<br>      name: &#39;isUnique&#39;,<br>      target: object.constructor,<br>      propertyName: propertyName,<br>      constraints: [],<br>      options: validationOptions,<br>      validator: UniqueValue,<br>    });<br>  };<br>}</pre><p><strong>You need to do 2 things to make it work. or you will get undefined error.</strong></p><h4>1. Add the module selector code to your <strong>main.ts</strong> file like the following</h4><pre>  useContainer(app.select(AppModule), { fallbackOnErrors: true });</pre><p>For your reference, once you added the code, your main.ts file looks like this…</p><pre>//main.ts<br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>...<br>import { useContainer } from &#39;class-validator&#39;;<br>...<br>...<br>import { ValidationPipe, UnprocessableEntityException } from &#39;@nestjs/common&#39;;<br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  const configService = app.get(ConfigService);<br>  ...<br>  ...<br>  app.useGlobalPipes(<br>    new ValidationPipe({<br>      transform: true<br>    })<br>  );<br>  useContainer(app.select(AppModule), { fallbackOnErrors: true }); // Added here.<br>  ...<br>  ...<br>  await app.listen(configService.get(&#39;PORT&#39;, 3001));<br>  console.log(`Application is running on: ${await app.getUrl()}`);<br>}<br>bootstrap();</pre><h4>2. Add UniqueValue class on providers of users module</h4><pre>//user.module.ts<br>@Module({<br>  imports: [<br>    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),<br>  ],<br>  controllers: [UsersController],<br>  providers: [UsersService, UniqueValue],// &lt;&lt; Added here. dont forgot import the file.<br>})<br>export class UsersModule {}</pre><p>If you found this helpful, be sure to leave a 💖 on the post.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e660fcfd1b49" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>