Mobile Input Masks
Format phone numbers, credit cards, and dates as users type using jQuery input masking that respects mobile keyboards.
Format phone numbers, credit cards, and dates as users type using jQuery input masking that respects mobile keyboards.
// Simple input mask without library
$(document).on("input", "#phone", function() {
let v = this.value.replace(/\D/g, "").slice(0, 10);
if (v.length > 6) v = `(${v.slice(0,3)}) ${v.slice(3,6)}-${v.slice(6)}`;
else if (v.length > 3) v = `(${v.slice(0,3)}) ${v.slice(3)}`;
this.value = v;
});
// Credit card
$(document).on("input", "#card", function() {
this.value = this.value.replace(/\D/g,"").slice(0,16).replace(/(.{4})/g,"$1 ").trim();
});
Always reposition the cursor after masking — use setSelectionRange() to avoid cursor jumping to end.