To prevent unexpected behavior and potential security risks from unvalidated user input.
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def create(conn, %{"user" => %{"name" => name}}) do
{:ok, user} = MyApp.Accounts.create_user(name)
render(conn, "show.html", user: user)
end
end
In this example, the user's name is accepted without validation. If a special character is included in the name, it can cause unexpected behavior or security vulnerabilities.
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def create(conn, %{"user" => %{"name" => name}}) do
case MyApp.Accounts.create_user(name) do
{:ok, user} ->
render(conn, "show.html", user: user)
{:error, changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
end
defmodule MyApp.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :name, :string
end
def changeset(user, attrs) do
user
|> cast(attrs, [:name])
|> validate_format(:name, ~r/^[a-zA-Z0-9_]*$/)
end
end
In the secure code, the user's name is validated using a regular expression, ensuring that it contains only alphanumeric characters and underscores. If the validation fails, an error is returned and can be handled by the controller.