MaratSH

MaratSH

Ecto schema and form's masked input correlation

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?

First 3 of 3 Posts Switch mode

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?

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
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
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement