MaratSH

MaratSH

Hello! I have a form where user inputs a phone (and other fields). I attach phx-hook to this input only, so it adds some masking for phone. Next, I have an ecto scheme and changeset to validate this input. When user inputs it masked, so validation handle_event function gets it like “+1 234 567 89 00” from params, but in ecto changeset i need to validate: is not empty (so only digits string should exist), starts from some number, the length should be i range and etc. So i create a new field where i delete all non digit symbols from incoming string, and validate this string for all i need. So, if i change input before pass it to changeset, it applies errors in “to_form(changeset)”, but it also changes input value. In other case, I create a new field in changeset, cast and validate it, so initial attrs didn’t change so form value didn’t change too. But it’s hard to relate validation errors from changeset to apply it in UI. How do you solve a problem like this? Did I miss a ready-made solution?

Showing Posts 1 to 3

woylie

woylie

If I understand your problem correctly, you want to validate the phone number and normalize the entered value when it is actually written to the database, is that correct? If so, you might want to have a look at Ecto.Changeset.prepare_changes/2.

MaratSH

MaratSH OP

Thanks for the answer! To clarify the topic, I’ll add a little code:

def render (assigns) do
...
<.simple_form
        for={@form}
        id="some-modal-form"
        phx-target={@myself}
        phx-change="validate"
        phx-submit="save"
      >
        <.input
          field={@form[:phone]}
          id="user-phone-number"
          type="text"
          label="Phone number"
          phx-hook="PhoneInput"
        />
...

def handle_event("validate", %{"some_input" => some_input} = props, socket) do
    changeset =
      SomeInput.changeset(%SomeInput{}, some_input)

    socket = socket |> assign(:form, to_form(changeset, action: :validate))
export const PhoneInput = {
    mounted() {
        this.el.addEventListener("input", e => {
            let match = this.el.value.replace(/\D/g, "")
                .match(/^(\d{1})(\d{3})(\d{3})(\d{2})(\d{2})$/)
                        //+1 234 567 89 00
            if(match) {
            this.el.value = `+${match[1]} ${match[2]} ${match[3]} ${match[4]} ${match[5]}`
            }
        })
    }
}
  @primary_key false
  embedded_schema do
    field :phone, :string
    field :name, :string
  end

  def changeset(some_input, attrs) do
    some_input
    |> cast(attrs, [:phone, :name])
    |> validate_phone(attrs)
    |> validate_name(attrs)
  end

  def validate_phone(changeset, attrs) do
    changeset
    |> validate_format(:phone, ~r/^1/, message: "Should start with 1")
    |> validate_length(:phone,
      is: 11,
      message: "Should be 11 characters long"
    )
    # |> more validatation cases here and in db phone will be stored as a string of 11 digits
  end

As you can see, i need to remove all non-digit symbols before validation pipes even only for validation.

woylie

woylie

I don’t think you need the hook here. You can define custom validation functions with Ecto.Changeset.validate_change/3. You can process the value in your custom validation function and then check the format. Or you can use Ecto.Changeset.update_change/3 to format the value before you run other validation functions.

You might want to consider using ExPhoneNumber for phone number validation, though. It will provide much better validation.

For storage, you should consider the e164 format. You can use ExPhoneNumber to convert the value into this format as well.

So roughly (not tested):

def changeset(schema, attrs) do
  schema
  |> cast(attrs, [:phone])
  |> validate_change(:phone, &validate_phone/2)
  |> prepare_changes(fn changeset ->
       if phone = get_change(changeset, :phone) do
         {:ok, phone_number} = ExPhoneNumber.parse(phone)
         ExPhoneNumber.format(phone_number, :e164)
       end
       changeset
     end)
end

def validate_phone(field, value) do
  case ExPhoneNumber.parse(value) do
    {:ok, _phone_number} ->
      # add further validation as needed on the parsed phone number
      []

    _ ->
      [{field, "invalid phone number"}]
  end
end
— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
psy-q
I’m trying to set up Emacs with elixir-ls via lsp-mode and credo via Flycheck. This should mostly be preconfigured as Flycheck picks up c...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews