Skip to content

Commit

Permalink
Merge pull request #89 from animina-dating/Virtual-branch-2
Browse files Browse the repository at this point in the history
Validate that mobile_phone is indeed a mobile phone number. closes #88
  • Loading branch information
wintermeyer authored Feb 28, 2024
2 parents a2eb571 + d23c5fe commit ef7ab34
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 33 deletions.
2 changes: 1 addition & 1 deletion lib/animina/accounts/resources/basic_user.ex
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ defmodule Animina.Accounts.BasicUser do
validate {Validations.Birthday, attribute: :birthday}
validate {Validations.PostalCode, attribute: :zip_code}
validate {Validations.Gender, attribute: :gender}
validate {Validations.PhoneNumber, attribute: :mobile_phone}
validate {Validations.MobilePhoneNumber, attribute: :mobile_phone}
end

identities do
Expand Down
2 changes: 1 addition & 1 deletion lib/animina/accounts/resources/user.ex
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ defmodule Animina.Accounts.User do
validate {Validations.Birthday, attribute: :birthday}
validate {Validations.PostalCode, attribute: :zip_code}
validate {Validations.Gender, attribute: :gender}
validate {Validations.PhoneNumber, attribute: :mobile_phone}
validate {Validations.MobilePhoneNumber, attribute: :mobile_phone}
end

identities do
Expand Down
46 changes: 46 additions & 0 deletions lib/animina/validations/mobile_phone_number.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
defmodule Animina.Validations.MobilePhoneNumber do
use Ash.Resource.Validation

@moduledoc """
This is a module for validating a mobile phone number.
"""

@impl true
def init(opts) do
case is_atom(opts[:attribute]) do
true -> {:ok, opts}
_ -> {:error, "attribute must be an atom!"}
end
end

@impl true
def validate(changeset, opts) do
Ash.Changeset.get_attribute(changeset, :mobile_phone)
|> extract_ex_phone_number()
|> validate_mobile_phone_number(opts)
end

defp extract_ex_phone_number(raw_attribute) do
case ExPhoneNumber.parse(raw_attribute, "DE") do
{:ok, phone_number} -> phone_number
_ -> nil
end
end

defp validate_mobile_phone_number(nil, opts) do
{:error, field: opts[:attribute], message: "must be a valid phone number"}
end

defp validate_mobile_phone_number(ex_phone_number, opts) do
case ExPhoneNumber.is_valid_number?(ex_phone_number) do
false ->
{:error, field: opts[:attribute], message: "must be a valid phone number"}

_ ->
case ExPhoneNumber.get_number_type(ex_phone_number) do
:mobile -> :ok
_ -> {:error, field: opts[:attribute], message: "must be a mobile phone number"}
end
end
end
end
31 changes: 0 additions & 31 deletions lib/animina/validations/phone_number.ex

This file was deleted.

0 comments on commit ef7ab34

Please sign in to comment.