LoginSignup
6
4

More than 1 year has passed since last update.

class-validatorでカスタムバリデータ定義

Last updated at Posted at 2022-09-14

class-validatorで「nullだけ」とか「undefinedだけ」のような独自のバリデーションを実装したい場合に、カスタムバリデータ(カスタムデコレータ)が使えますという備忘録です。

前提

動作確認時のclass-validatorのversionは以下の通りです。
class-validator: v0.13.2

課題: nullとundefinedを個別に判定したい

IsOptional

@IsOptional()を使うと、nullundefinedの場合両方許容してしまいます。

参考: https://github.com/typestack/class-validator#validation-decorators@IsOptional()

そのため、以下のようなケースでうまいことclass-validatorが機能しません。困った。

// nullableだけどundefinedではない
nullableString: string | null

// optionalだけどnullではない
optionalString?: stirng;

ValidateIf

特定条件を満たす場合にのみバリデーションするという条件をValidateIfで付加できます。

参考: https://github.com/typestack/class-validator#conditional-validation

従って、例えば上記のoptionalStringに対するバリデーションでundefinedのみを許容したい場合、

@ValidateIf((_, value) => value !== undefined)
optionalString?: string;

と書けます。@ValidateIf(...)をカスタムデコレータとして定義しておけば、

const IsUndefinedable = () => {
  return ValidateIf((_, value) => value !== undefined)
}

~~~

@IsUndefindable()
optionalString?: string;

のように書けて便利です。

結論

ValidateIfデコレータは便利です。

余談ですが、ValidateIfの第一引数では、当該ValidateIfが定義されている対象オブジェクトのプロパティを参照できるようなので、公式の例にあるように、別プロパティを使って条件組むことも可能です。

// https://github.com/typestack/class-validator#conditional-validationから引用
import { ValidateIf, IsNotEmpty } from 'class-validator';

export class Post {
  otherProperty: string;

  @ValidateIf(o => o.otherProperty === 'value')
  @IsNotEmpty()
  example: string;
}
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4