Phoenix username 限定長度值

2023-12-18 14:20 更新

這一章里,我們要限制 username 的長度值,兩個(gè)錯(cuò)誤提示分別如下:

  1. 用戶名最短 3 位
  2. 用戶名最長 15 位

老規(guī)矩,先寫測試:

diff --git a/test/tv_recipe/users_test.exs b/test/tv_recipe/users_test.exs
index 73fc189..26a7735 100644
--- a/test/tv_recipe/users_test.exs
+++ b/test/tv_recipe/users_test.exs
@@ -53,4 +53,16 @@ defmodule TvRecipe.UserTest do
     attrs = %{@valid_attrs | username: "陳三"}
     assert %{username: ["用戶名只允許使用英文字母、數(shù)字及下劃線"]} = errors_on(%User{}, attrs)
   end
+
+  test "username's length should be larger than 3" do
+    attrs = %{@valid_attrs | username: "ab"}
+    changeset = User.changeset(%User{}, attrs)
+    assert %{username: ["用戶名最短 3 位"]} = errors_on(changeset)
+  end
+
+  test "username's length should be less than 15" do
+    attrs = %{@valid_attrs | username: String.duplicate("a", 16)}
+    changeset = User.changeset(%User{}, attrs)
+    assert %{username: ["用戶名最長 15 位"]} = errors_on(changeset)
+  end
 end

顯然,我們新增的這兩個(gè)測試會(huì)失敗,因?yàn)槲覀冞€沒有加上限制規(guī)則。

打開 lib/tv_recipe/users/user.ex 文件,添加兩條規(guī)則:

diff --git a/lib/tv_recipe/users/user.ex b/lib/tv_recipe/users/user.ex
index 7d7d59f..8c68e6d 100644
--- a/lib/tv_recipe/users/user.ex
+++ b/lib/tv_recipe/users/user.ex
@@ -17,6 +17,8 @@ defmodule TvRecipe.User do
     |> cast(params, [:username, :email, :password])
     |> validate_required([:username, :email, :password], message: "請(qǐng)?zhí)顚?)
     |> validate_format(:username, ~r/^[a-zA-Z0-9_]+$/, message: "用戶名只允許使用英文字母、數(shù)字及下劃線")
+    |> validate_length(:username, min: 3, message: "用戶名最短 3 位")
+    |> validate_length(:username, max: 15, message: "用戶名最長 15 位")
     |> unique_constraint(:username, name: :users_lower_username_index, message: "用戶名已被人占用")
     |> unique_constraint(:email)
   end

validate_length 用于驗(yàn)證字段的長度值,min 參數(shù)用于指定最小值。

現(xiàn)在運(yùn)行測試,悉數(shù)通過。

你可能已經(jīng)發(fā)現(xiàn),我們有大量類似 validate_length、validate_format 的函數(shù)可以使用,我們要做的,只是定義我們的需求,然后找出相應(yīng)的函數(shù) - 非常輕松。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)