password
的規(guī)則與 email 規(guī)則類似,同樣有三條:
限制 | 錯誤提示 |
---|---|
必填 | 請?zhí)顚?/td> |
密碼最短 6 位 | 密碼最短 6 位 |
密碼不能明文存儲在數(shù)據(jù)庫中 | - |
但我們會分兩章完成,這一章里完成前面兩條規(guī)則,“密碼不能明文存儲”規(guī)則因為較復(fù)雜,所以放到下一章里。
首先,是添加兩個測試:
diff --git a/test/tv_recipe/users_test.exs b/test/tv_recipe/users_test.exs
index 82dcf6a..8689f4e 100644
--- a/test/tv_recipe/users_test.exs
+++ b/test/tv_recipe/users_test.exs
@@ -102,4 +102,14 @@ defmodule TvRecipe.UserTest do
assert {:error, changeset} = TvRecipe.Repo.insert(another_user_changeset)
assert %{email: ["郵箱已被人占用"]} = errors_on(changeset)
end
+
+ test "password is required" do
+ attrs = %{@valid_attrs | password: ""}
+ assert %{password: ["請?zhí)顚?]} = errors_on(%User{}, attrs)
+ end
+
+ test "password's length should be larger than 6" do
+ attrs = %{@valid_attrs | password: String.duplicate("1", 5)}
+ assert %{password: ["密碼最短 6 位"]} = errors_on(%User{}, attrs)
+ end
end
一個驗證 password
必填,一個驗證密碼長度。
這兩個測試,必填的一個會通過,因為在處理 username
時一起處理了;驗證密碼長度的則會失敗,因為我們的規(guī)則還沒寫。
打開 user.ex
文件,添加一行 validate_length
:
diff --git a/lib/tv_recipe/users/user.ex b/lib/tv_recipe/users/user.ex
index 9307a3c..3069e79 100644
--- a/lib/tv_recipe/users/user.ex
+++ b/lib/tv_recipe/users/user.ex
@@ -23,5 +23,6 @@ defmodule TvRecipe.User do
|> unique_constraint(:username, name: :users_lower_username_index, message: "用戶名已被人占用")
|> validate_format(:email, ~r/@/, message: "郵箱格式錯誤")
|> unique_constraint(:email, name: :users_lower_email_index, message: "郵箱已被人占用")
+ |> validate_length(:password, min: 6, message: "密碼最短 6 位")
end
end
再運(yùn)行測試,全部通過。
這樣,我們就完成了 password
的前兩條驗證規(guī)則。
更多建議: