LoginSignup
0
0

More than 1 year has passed since last update.

#Slack アプリ開発:モーダルでのバリデーションについて

Last updated at Posted at 2022-01-18

Slack___local_SlaIM___George_Dev.png

モーダル、使ってますか?
めちゃ使っているのですが、今回はバリデーションについてです。
上記のようなモーダルを作っているのですが、URL欄にはhttpが含まれたものがほしい。ユーザーIDはユニークじゃないとだめなので、重複した場合はエラーを返したいという場合にどうしましょう。というものです。

答えはこちらに書かれています

入力ウィンドウのビューはこんな形で開かれています。

        client.views_update(
            view_id=body["view"]["id"],
            hash=body["view"]["hash"],
            view={
                "type": "modal",
                # ビューの識別子
                "callback_id": "view_1",
                "title": {"type": "plain_text", "text": text_title},
                "submit": {"type": "plain_text", "text": text_submit},
                "private_metadata": json.dumps(private_metadata),
                "blocks": blocks
            }
        )

ビューの識別子に当たる部分で、submitの結果を受けるという形です。

@app.view("view_1")
def handle_submission(ack, body, client, view, logger):
    # `input_c`という block_id に `dreamy_input` を持つ input ブロックがある場合
    hopes_and_dreams = view["state"]["values"]["input_c"]["dreamy_input"]
    user = body["user"]["id"]
    # 入力値を検証
    errors = {}
    if hopes_and_dreams is not None and len(hopes_and_dreams) <= 5:
        errors["input_c"] = "The value must be longer than 5 characters"
    if len(errors) > 0:
        ack(response_action="errors", errors=errors)
        return

入力値を検証と書かれた部分バリデーションをかけています。

errors["input_c"]の部分が、blocksのblock_idを指します。
該当するblock_idが存在していた場合、submit自体はキャンセルされて、元のモーダルの入力欄にエラーメッセージを表示することができるという仕組みになっています。

全然気付いてなかった…。便利なので使っていきましょう。

仕様についてはこちらも参照

おまけ

もともとは、submit_disabled属性を使おうとしていましたが、こちらはワークフローのみでしか使えないということでした。
バリデーションが通ってない場合はこんなふうにすれば送信ボタンがアクティブにならないだろうと思っていたんですよね。
それは出来ませんのでご注意ください。

client.views_open(
            trigger_id=body["trigger_id"],
            view={
                "type": "modal",
                # ビューの識別子
                "callback_id": "callback_id",
                "title": {"type": "plain_text", "text": text_title},
                "submit": {"type": "plain_text", "text": text_submit},
                "submit_disabled": True,#←このような設定は出来ない
                "blocks": blocks
            }
        )
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