16

I want to validate Address field, it may contains numbers or strings, but it should not accept continioues empty spaces

@IsAlphaNUmereic() Address: string;

i want that, Address can be numeric or alphabetic... but it should not accepts continues empty spaces

GaneSH
  • 543
  • 2
  • 5
  • 16

5 Answers5

33

An alternative solution without custom validation decorators would be:

@IsNotEmpty()
@Transform(({ value }: TransformFnParams) => value?.trim())
Address: string;
Markus
  • 1,222
  • 1
  • 13
  • 26
  • 1
    the `.trim()` might crash if the `value` variable is null, undefined or any other type other than string. Should add an "optional chaining" like @razouq did in his answer below: https://stackoverflow.com/a/69595889/12056841 – Shani Kehati Feb 26 '22 at 21:28
  • 1
    Thanks @ShaniKehati, you are correct without it, it crashed. Please edit the answer – Cpp crusaders May 11 '22 at 07:20
  • @Markus what is the TransformFnParams ? where can I import that? – huykon225 May 25 '22 at 04:35
  • 1
    @huykon225 `import { TransformFnParams } from 'class-transformer';` – Markus May 26 '22 at 12:19
  • About usage of "optional chaining" necessity, is this still valid? I have tried with/without IsNotEmpty, if value is undefined, Transform cb never called? @ShaniKehati – Caner Sezgin Jun 24 '22 at 08:37
  • @CanerSezgin https://github.com/typestack/class-validator/blob/2ef8ff0f32be53e75dade2a0b86b158d87427176/src/decorator/common/IsNotEmpty.ts#L10 You might be correct, but, I won't rely on that- I would still make sure to check that the variable in `@Transform` decorator can be `trim`ed. **The best** would be to check `typeof value==="string"?value.trim():""` – Shani Kehati Jun 27 '22 at 06:49
  • @ShaniKehati your solution doesn't work with me – esraa Feb 19 '23 at 19:05
  • Hi, I added type-validation suggestion to the given answer, can I help you with something? What doesn't work? @esraa – Shani Kehati Feb 20 '23 at 13:03
  • I agree with Shani. In the case of a number, for example, optional chaining will not prevent the trim() method from being called on it, which will lead to a crash. – Yehezkel Jun 13 '23 at 07:21
18

Afaik there's no support for a "isNotBlank"-decorator, but you can just write one yourself:

import { registerDecorator, ValidationOptions } from "class-validator";

export function IsNotBlank(property: string, validationOptions?: ValidationOptions) {
    return function (object: Object, propertyName: string) {
        registerDecorator({
            name: "isNotBlank",
            target: object.constructor,
            propertyName: propertyName,
            constraints: [property],
            options: validationOptions,
            validator: {
                validate(value: any) {
                    return typeof value === "string" && value.trim().length > 0;
                }
            }
        });
    };
}

You would then add this custom validator to your existing one:

@IsNotBlank()
@IsAlphaNumeric()
Address: string;

Checkout https://github.com/typestack/class-validator#custom-validation-decorators for more information regarding custom validators.

eol
  • 23,236
  • 5
  • 46
  • 64
3
@IsNotEmpty()
@Transform((({value}): string) => value?.trim())
Address: string;

destructure the 'value' after that you can trim it

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
razouq
  • 101
  • 3
  • 1
    you shouldn't assign the `string` type to the `value` variable because it could be anything. Should just follow the `TransformFnParams` type. just like @Markus suggested in his answer above: https://stackoverflow.com/a/64842927/12056841 – Shani Kehati Feb 26 '22 at 21:24
2

You can use the the @NotContains class validator. DTO should like this:

@IsAlphaNUmereic()
@NotContains(" ")
address: string
ZinnieZee
  • 21
  • 3
0

Here is the best way to validate your key: Import the required properties:

import { IsNotEmpty,Length,NotContains } from "class-validator";
import { Transform } from 'class-transformer';
import { ApiProperty } from "@nestjs/swagger";

Create a class for the payload:

export class SomePayloadCheckDto {
  @ApiProperty({ required: true })
  @IsNotEmpty()
  @NotContains(" ")
  @Transform(({ value }) => value?.trim())
  @Length(3, 20)
  someString: string;
}
Shubham Verma
  • 8,783
  • 6
  • 58
  • 79