Phoenix username 只允許使用英文字母、數(shù)字及下劃線

2023-12-18 14:20 更新

我們擬定的規(guī)則里,username 將只允許使用英文字母、數(shù)字下劃線。而目前樣板生成的文件里,我們可以使用任何字符。

我們用測試來驗證一下。

打開 test/tv_recipe/users_test.exs 文件,添加一個測試:

diff --git a/test/tv_recipe/users_test.exs b/test/tv_recipe/users_test.exs
index 975c7b1..644f4c3 100644
--- a/test/tv_recipe/users_test.exs
+++ b/test/tv_recipe/users_test.exs
@@ -42,4 +42,10 @@ defmodule TvRecipe.UserTest do
     assert {:error, changeset} = TvRecipe.Repo.insert(another_user_changeset)
     assert %{username: ["用戶名已被人占用"]} = errors_on(changeset)
   end
+
+  test "username should only contains [a-zA-Z0-9_]" do
+    attrs = %{@valid_attrs | username: "陳三"}
+    changeset = User.changeset(%User{}, attrs)
+    refute changeset.valid?
+  end
 end

命令行下運行測試得到的結(jié)果是:

mix test test/tv_recipe/users_test.exs
..

  1) test username should only contains [a-zA-Z0-9_] (TvRecipe.UserTest)
     test/tv_recipe/users_test.exs:46
     Expected false or nil, got true
     code: changeset.valid?()
     stacktrace:
       test/tv_recipe/users_test.exs:49: (test)

...

Finished in 0.1 seconds
6 tests, 1 failure

在我們的規(guī)則里,用戶名“陳三”是不允許的,但測試結(jié)果顯示,目前它的被允許的。

顯然,我們需要添加一個規(guī)則,在哪兒?怎么定義?

還是在 lib/tv_recipe/users/user.ex 文件中。

要限制字符,我們使用 validate_format

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

~r/^[a-zA-Z0-9_]+$/ 是 elixir 的正則表達式,你如果不熟悉,可以試試這個在線工具 http://www.elixre.uk/。

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

但我們還要再加一個測試,用于驗證用戶名格式出錯時的提示信息。

diff --git a/test/tv_recipe/users_test.exs b/test/tv_recipe/users_test.exs
index 644f4c3..73fc189 100644
--- a/test/tv_recipe/users_test.exs
+++ b/test/tv_recipe/users_test.exs
@@ -48,4 +48,9 @@ defmodule TvRecipe.UserTest do
     changeset = User.changeset(%User{}, attrs)
     refute changeset.valid?
   end
+
+  test "changeset with invalid username should throw errors" do
+    attrs = %{@valid_attrs | username: "陳三"}
+    assert %{username: ["用戶名只允許使用英文字母、數(shù)字及下劃線"]} = errors_on(%User{}, attrs)
+  end
 end

運行測試,悉數(shù)通過。

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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號