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: ["用户名只允许使用英文字母、数字及下划线"]} = 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
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: "请填写")
|> validate_format(:username, ~r/^[a-zA-Z0-9_]+$/, message: "用户名只允许使用英文字母、数字及下划线")
+ |> 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