Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating empty space in class validator

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

like image 662
GaneSH Avatar asked Mar 25 '19 07:03

GaneSH


3 Answers

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.

like image 111
eol Avatar answered Sep 25 '22 20:09

eol


An alternative solution without custom validation decorators would be:

@IsNotEmpty()
@Transform(({ value }: TransformFnParams) => value.trim())
Address: string;
like image 27
Markus Avatar answered Sep 23 '22 20:09

Markus


@IsNotEmpty()
@Transform((({value}): string) => value?.trim())
Address: string;

destructure the 'value' after that you can trim it

like image 22
razouq Avatar answered Sep 26 '22 20:09

razouq