From b1070686ed636d3a978e017ca1acfe8f7da1cb92 Mon Sep 17 00:00:00 2001 From: dew Date: Wed, 11 Sep 2024 21:10:07 +0700 Subject: [PATCH] Add phone number formatting to registration form --- .../controllers/phone_format_controller.js | 27 +++++++++++++++++++ app/views/registrations/new.html.erb | 5 +++- 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 app/javascript/controllers/phone_format_controller.js diff --git a/app/javascript/controllers/phone_format_controller.js b/app/javascript/controllers/phone_format_controller.js new file mode 100644 index 0000000..4e5038d --- /dev/null +++ b/app/javascript/controllers/phone_format_controller.js @@ -0,0 +1,27 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + static targets = ["input"] + + connect() { + this.inputTarget.addEventListener('input', this.formatPhoneNumber.bind(this)) + } + + formatPhoneNumber(event) { + const input = event.target + let value = input.value.replace(/\D/g, '') // Remove non-numeric characters + + if (value.length > 10) { + value = value.slice(0, 10) + } + + // Format the value + if (value.length > 6) { + value = value.replace(/(\d{3})(\d{3})(\d{0,4})/, '$1-$2-$3') + } else if (value.length > 3) { + value = value.replace(/(\d{3})(\d{0,3})/, '$1-$2') + } + + input.value = value + } +} diff --git a/app/views/registrations/new.html.erb b/app/views/registrations/new.html.erb index a3785bb..abae0dc 100644 --- a/app/views/registrations/new.html.erb +++ b/app/views/registrations/new.html.erb @@ -57,7 +57,10 @@
<%= form.label :phone_number %> - <%= form.text_field :phone_number, class: 'form-control' %> + <%= form.text_field :phone_number, + placeholder: '123-456-7890', + class: 'form-control', + data: { controller: "phone-format", phone_format_target: "input" } %>
<%= @registration.errors.full_messages_for(:phone_number).join(', ') %>