简体   繁体   中英

How to set fallback value if validation fails (NestJS, class-validator)

I have a Person class similar to the one described below. languages is an optional property. It may be missing or invalid. I don't want the post call to fail if languages is missing or invalid. Instead, I want to set languages to a fallback value, say ["en"] .

How would I do that?

I've looked into custom validators, but that doesn't seem to fit, since I want to both run all the validations and also change the object if it fails validation.

// interface
import { IsString, MinLength, IsNotEmpty } from 'class-validator';

class Person {
  @IsNotEmpty()
  public readonly name: string;

  @IsArray()
  @IsString({ each: true })
  @MinLength(1)
  public languages: string[];  // <-- how would I specify a fallback value?
}
// controller
import { Body, Controller, Post } from "@nestjs/common";

@Controller("signup")
export class SignupController {
   @Post()
   public async submit(@Body() formData: Person) {
      // create the user object and save it to the db
   }

}

I ended up using @Transform like this

import { Transform } from "class-transformer";
import { IsOptional } from 'class-validator';

class Person {
    @IsOptional()
    @Transform(({ value }) => {
        if (/* test for value validity */) {
            return value as string[];
        }
        return fallbackLanguages;
    })
    public languages: string[];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM