国产chinesehdxxxx野外,国产av无码专区亚洲av琪琪,播放男人添女人下边视频,成人国产精品一区二区免费看,chinese丰满人妻videos

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

2023-12-18 14:20 更新

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

我們用測(cè)試來(lái)驗(yàn)證一下。

打開 test/tv_recipe/users_test.exs 文件,添加一個(gè)測(cè)試:

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

命令行下運(yùn)行測(cè)試得到的結(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ī)則里,用戶名“陳三”是不允許的,但測(cè)試結(jié)果顯示,目前它的被允許的。

顯然,我們需要添加一個(gè)規(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: "請(qǐng)?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 的正則表達(dá)式,你如果不熟悉,可以試試這個(gè)在線工具 http://www.elixre.uk/

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

但我們還要再加一個(gè)測(cè)試,用于驗(yàn)證用戶名格式出錯(cuò)時(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

運(yùn)行測(cè)試,悉數(shù)通過(guò)。

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

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)