class-validator: ensures the correct number of digits are present in numeric values

Seeking assistance on validating the number of digits for numeric values using class-validator. Specifically, I want my entity to only accept numbers with 6 digits for a certain property. For example:

const user1 = new User();
user1.code = 123456 // should be valid

const user2 = new User();
user2.code = 12345 // should be invalid

const user3 = new User();
user3.code = 1234567 // should be invalid

I attempted to use IsNumber, MinLength, and MaxLength together, but it didn't work as expected.

class User {
    @IsPositive()
    @IsNotEmpty()
    @IsNumber({ maxDecimalPlaces: 0 })
    @MinLength(6)
    @MaxLength(6)
    public code: number;
}  

Getting an error message stating that

code must be shorter than or equal to 6 characters
.

If anyone has any guidance, I would greatly appreciate it!

Answer №1

To verify the length of a string, MinLength and MaxLength are typically employed; however, in this case, please be aware that the property being referenced is numerical in nature. To ensure it meets the criteria of a six-digit number, I recommend substituting Min and Max instead. For instance, utilizing @Min(100000) and @Max(999999) should suffice for this purpose.

Answer №2

Adding my two cents to mention that you could also achieve the same result using a regular expression like @Matches(/^\d{6}$/).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular Bootstrap: How to Resolve the Error "Function $(...).collapse() is Undefined"

I'm a beginner with Bootstrap and I'm attempting to trigger the .collapse() function using JavaScript within an Angular controller when a user clicks on a link. The goal is to close the collapsible navbar when a link is clicked, as the routing in ...

Prevent the creation of references to objects passed as function parameters in a separate list

I'm facing an issue with modifying items from an array and adding them to a new list of objects. The problem arises when I make changes to the item in the new list, it also reflects those changes in the original array. It seems like there is some ref ...

The IP validation feature in the textbox is not performing as anticipated

My goal is to have a textbox that receives an IP address and validates it before submission. To achieve this, I've developed a JavaScript class called `validityCheck`. In my main Vue.js component, I aim to utilize this class to validate the input&apo ...

convert a string to JSON format using Node.js Express

Currently, I am viewing some string data in a browser that has been processed using python-node js express. The data looks something like this: In order to manipulate the data more effectively, I would like to convert it into JSON format that follows this ...

Error message '[object Error]' is being returned by jQuery ajax

I'm currently facing a challenge with my HTML page that calls an API. Every time I attempt to run it, I encounter an [object Error] message. Below is the code snippet in question: jQuery.support.cors = true; jQuery.ajax({ type: "POST", url: ...

The online server is unable to access the route from the ajax function in a separate JavaScript file

I am currently working on a Laravel project where each view page has its own separate JS file. However, I have encountered an issue when trying to access route functions from AJAX post or get calls on the online server (Digital Ocean). The error message I ...

Even with e.preventDefault, the anchor link still opens in a new tab on the browser

I am dealing with an ajax call that triggers a REST API to return a list of all names, as well as another REST API that matches those names. For instance: /list returns: list1, list2, list3 and /api/list1.json returns: JSON data for list1.. Currently, ...

What is the reason for receiving an error with one loop style while the other does not encounter any issues?

Introduction: Utilizing TypeScript and node-pg (Postgres for Node), I am populating an array of promises and then executing them all using Promise.all(). While pushing queries into an array during iteration over a set of numbers, an error occurs when the ...

How can React Components be imported into a website that is not built with React?

After developing a site with Node and Express, I am looking to incorporate a page built with React and JSX. As part of this process, I have installed Babel as an npm package and included React in the index.html file like so: <script src="https://un ...

Looking for a fully customizable event and booking calendar?

Currently, I am searching for a unique event and booking calendar that provides the ability to customize each cell or day with our desired content. While most calendars only allow for inputting events as text, we require a solution that enables us to add ...

React JS Calendar

I'm currently working on a project where I need to create a calendar component using React. The design requires the days to be displayed like in the Windows calendar, starting from Sunday even if it's another month and ending with Saturday. The ...

Developing a Cloud Function for Stripe that is taking forever to finalize writing data to Firestore

Currently, I am facing an issue with my Google Cloud function (provided below) that handles webhooks from Stripe payments and stores some data in Firestore. The problem is that it seems to hang for approximately 3 minutes before completing. const Stripe = ...

Feeling lost when it comes to forms and hitting that submit button?

Below is a sample form structure: <html> <head> <title>My Page</title> </head> <body> <form name="myform" action="http://www.abcdefg.com/my.cgi" method="POST"> <div align="center"> <br><br; <br& ...

Angular Testing - issue with promise returning unexpected results

I'm having trouble with populating vm.chartData in my HomeCtrl. Even though I've mocked data to it in the beforeEach() function, when I console.log(scope.vm.chartData), it returns undefined. However, other scope variables like graphLoading are pr ...

Steps for deploying an ejs website with winscp

I have developed a Node.js web application using ExpressJS, with the main file being app.js. Now I need to publish this website on a domain using WinSCP. However, WinSCP requires an index.html file as the starting point for publishing the site. Is there ...

Issues with visuals in jQuery.animate

I have nearly finished implementing a slide down drawer using jQuery. The functionality I am working on involves expanding the drawer downwards to reveal its content when the handle labeled "show" is clicked, and then sliding the drawer back up when the ha ...

Background image fixed with scrolling effect

I've been struggling with a parallax effect on my website. After seeing it work smoothly on other websites, I tried to implement it myself but couldn't quite get it right. The background image keeps moving when I scroll the page and I want it to ...

React hooks causing dynamic object to be erroneously converted into NaN values

My database retrieves data from a time series, indicating the milliseconds an object spends in various states within an hour. The format of the data is as follows: { id: mejfa24191@$kr, timestamp: 2023-07-25T12:51:24.000Z, // This field is dynamic ...

Error: The specified module 'sqlite' does not have an export named 'default' as requested

Having some difficulty with importing sqlite into my project. When I add this line: import sqlite from 'sqlite'; An error occurs: file:///D:/WebPro/WebProg/cwCode/dbInteract.js:2 import sqlite from 'sqlite'; ^^^^^^ SyntaxError: ...

The loop is being controlled but the data is not being added and shown in the HTML div

I am struggling to display JSON data in an HTML div using a for loop. While my control is entering the loop, the data is not being appended and displayed in the HTML div. Here is the JSON data: [{"id":"15","FirstName":"ranjan","MiddleName":"","LastName": ...