如何在nestjs中接受空值或字符串字段

huangapple go评论77阅读模式
英文:

how to accept both null or string field in nestjs

问题

Here is the translated code:

import {
  IsDefined,
  IsString,
  IsEmail,
  IsOptional,
  Allow,
} from 'class-validator';
import { BaseCommand } from 'shared/commands/BaseCommand';

export class RegisterCommand extends BaseCommand {

  @IsDefined()
  @IsString()
  lastName: string;

  @IsDefined()
  @IsEmail()
  email: string;

  @IsOptional()
  @Allow()
  @IsString()
  password?: string | null;
}

Regarding your issue, it seems like you're using the class-validator library for validation. To allow users to register with or without a password, you can make the password property optional in your RegisterCommand class, which you have already done with @IsOptional().

However, it's important to note that the error you're seeing is related to the validation process, not whether you allow a null or undefined password. To avoid the validation error, you should ensure that when a user doesn't provide a password, you set the password property to null (or undefined) explicitly in your code before passing the object for validation. This way, the validation will pass without errors when no password is provided.

英文:
import {
  IsDefined,
  IsString,
  IsEmail,
  IsOptional,
  Allow,
} from 'class-validator';
import { BaseCommand } from 'shared/commands/BaseCommand';

export class RegisterCommand extends BaseCommand {

  @IsDefined()
  @IsString()
  lastName: string;

  @IsDefined()
  @IsEmail()
  email: string;

  @IsOptional()
  @Allow()
  @IsString()
  password?: string | null;
}

I have to accept either if user enter a password or also if I want don't want to allow them to enter password (because I want to implement google login and need to store email and name in db) then how can I achieve this?

currenyly I am getting error:

 response: {
    statusCode: 400,
    message: [
      'password should not be null or undefined',
      'password must be a string'
    ],
    error: 'Bad Request'
  },

答案1

得分: 1

If you need to allow explicit null values, you will have to create a custom validator. Here's how to do it with a custom validator:

import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, registerDecorator, ValidationOptions } from 'class-validator';

@ValidatorConstraint({ name: 'IsStringOrNull', async: false })
export class IsStringOrNullConstraint implements ValidatorConstraintInterface {
    validate(value: any, args: ValidationArguments) {
        return typeof value === 'string' || value === null; // for async validations you must return a Promise<boolean> here
    }

    defaultMessage(args: ValidationArguments) {
        return 'Text ($value) must be a string or null!';
    }
}

export function IsStringOrNull(validationOptions?: ValidationOptions) {
    return function (object: Object, propertyName: string) {
        registerDecorator({
            name: 'IsStringOrNull',
            target: object.constructor,
            propertyName: propertyName,
            constraints: [],
            options: validationOptions,
            validator: IsStringOrNullConstraint,
        });
    };
}

and then use it like so:

@IsDefined()
@IsStringOrNull()
password?: string | null;

See if this will solve your issue.

英文:

If you need to allow explicit null values, you will have to create a custom validator. Here's how to do it with a custom validator:

import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, registerDecorator, ValidationOptions } from &#39;class-validator&#39;;

@ValidatorConstraint({ name: &#39;IsStringOrNull&#39;, async: false })
export class IsStringOrNullConstraint implements ValidatorConstraintInterface {
    validate(value: any, args: ValidationArguments) {
        return typeof value === &#39;string&#39; || value === null; // for async validations you must return a Promise&lt;boolean&gt; here
    }

    defaultMessage(args: ValidationArguments) {
        return &#39;Text ($value) must be a string or null!&#39;;
    }
}

export function IsStringOrNull(validationOptions?: ValidationOptions) {
    return function (object: Object, propertyName: string) {
        registerDecorator({
            name: &#39;IsStringOrNull&#39;,
            target: object.constructor,
            propertyName: propertyName,
            constraints: [],
            options: validationOptions,
            validator: IsStringOrNullConstraint,
        });
    };
}

and then use it like so:

@IsDefined()
@IsStringOrNull()
password?: string | null;

See if this will solve your issue.

huangapple
  • 本文由 发表于 2023年6月30日 01:22:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定