-
Notifications
You must be signed in to change notification settings - Fork 0
/
exceptions.ex
77 lines (60 loc) · 1.83 KB
/
exceptions.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
defmodule User do
defstruct [:login, :password, :name]
@type t :: %User{}
end
defmodule ValidateUserGood do
@type validate_error :: :invalid_login | :invalid_password | :invalid_name
@spec validate(User.t) :: :ok | {:error, validate_error}
def validate(%User{} = user) do
with :ok <- validate_login(user),
:ok <- validate_password(user),
:ok <- validate_name(user)
do
:ok
else
error -> {:error, error}
end
end
@login_re ~r/\A\w{5,20}\z/
@min_password_length 8
@name_re ~r/\A[\w ]+\z/
defp validate_login(%User{login: login}) do
if Regex.match?(@login_re, login), do: :ok, else: :invalid_login
end
defp validate_password(%User{password: password}) do
if String.length(password) >= @min_password_length, do: :ok, else: :invalid_password
end
defp validate_name(%User{name: name}) do
if Regex.match?(@name_re, name), do: :ok, else: :invalid_name
end
end
defmodule ValidateUserBad do
defmodule LoginError do
defexception message: "invalig login"
end
defmodule PasswordError do
defexception message: "invalig password"
end
defmodule NameError do
defexception message: "invalig name"
end
@spec validate!(User.t) :: :ok | no_return # WOW, such useful, very functional
def validate!(%User{} = user) do
validate_login!(user)
validate_password!(user)
validate_name!(user)
:ok
end
@login_re ~r/\A\w{5,20}\z/
@min_password_length 8
@name_re ~r/\A[\w ]+\z/
defp validate_login!(%User{login: login}) do
unless Regex.match?(@login_re, login), do: raise LoginError
end
defp validate_password!(%User{password: password}) do
unless String.length(password) >= @min_password_length, do: raise PasswordError
end
defp validate_name!(%User{name: name}) do
unless Regex.match?(@name_re, name), do: raise NameError
end
end