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

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews