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
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
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: "请填写")
+ |> validate_format(:username, ~r/^[a-zA-Z0-9_]+$/, message: "用户名只允许使用英文字母、数字及下划线")
|> unique_constraint(:username, name: :users_lower_username_index, message: "用户名已被人占用")
|> unique_constraint(:email)
end
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: ["用户名只允许使用英文字母、数字及下划线"]} = errors_on(%User{}, attrs)
+ end
end