Skip to content

Commit

Permalink
Add phone number formatting to registration form
Browse files Browse the repository at this point in the history
  • Loading branch information
natthaphong1939 committed Sep 11, 2024
1 parent 27cbc13 commit b107068
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
27 changes: 27 additions & 0 deletions app/javascript/controllers/phone_format_controller.js
Original file line number Diff line number Diff line change
@@ -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
}
}
5 changes: 4 additions & 1 deletion app/views/registrations/new.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@

<div class="form-group">
<%= 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" } %>
<div class="error-message" >
<%= @registration.errors.full_messages_for(:phone_number).join(', ') %>
</div>
Expand Down

0 comments on commit b107068

Please sign in to comment.