0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Angular カスタムバリデーションの実装方法

Last updated at Posted at 2024-07-11

まずはコード例。
以下例ではわざわざカスタムする必要のない基本的なチェックを行なっていますが、これを元に独自のバリデーションを実装できます。

customValidator(): ValidatorFn {
    return (control: FormControl): {[key: string]: any} => {
      let val: number = control.value;

      if(!val) {
        // 必須
        return {"commonValidator": true};
      }

      if(/\D/.test(val.toString())) {
        // 数値のみ
        return {"commonValidator": true};
      } else if (val < 0) {
        // 0以上
        return {"commonValidator": true};
      }

      return null;
    }
};

Angularのリアクティブフォームに適用されるカスタムバリデーション関数 customValidator の説明です。

カスタムバリデーション関数

customValidatorValidatorFn 型の関数を返します。この関数は、FormControl オブジェクトを受け取り、バリデーション結果を表すオブジェクトまたは null を返します。バリデーションのロジックは以下の通りです:

  • 必須チェック:
    • 値が nullundefined、または空文字列の場合、エラーを返します。
if(!val) {
  // 必須
  return {"commonValidator": true};
}
  • 数値チェック:
    • 値が数値以外の文字を含む場合、エラーを返します。
if(/\D/.test(val.toString())) {
  // 数値のみ
  return {"commonValidator": true};
}
  • 非負数チェック:
    • 値が0未満の場合、エラーを返します。
if(val < 0) {
  // 0以上
  return {"commonValidator": true};
}

バリデーションが失敗すると、エラーオブジェクト { "commonValidator": true } を返し、フォームコントロールは無効な状態になります。バリデーションが成功すると、null を返し、フォームコントロールは有効な状態になります。

使用例

このバリデータは、以下のようにフォームコントロールに適用することができます:

this.form = new FormGroup({
  someNumber: new FormControl('', [ThresholdSettingComponent.commonValidator()])
});

この設定により、someNumber フィールドに対して、上記のバリデーションルールが適用されます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?