if i enter 3064758254 the inputMask js library automatically converts it into like this (306)475-8254 How can I do this without inputMask library?
2 Answers
You can do this using javascript, fiddle link is https://jsfiddle.net/tr59bocw/1/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Phone Number Formatter</title>
</head>
<body>
<form>
<label for="phone-input">Phone Number:</label>
<input type="text" id="phone-input" name="phone" maxlength="14" placeholder="(306)475-8254">
</form>
<script>
document.addEventListener("DOMContentLoaded", function() {
const phoneInput = document.getElementById("phone-input");
phoneInput.addEventListener("input", function(event) {
let value = phoneInput.value.replace(/\D/g, ""); // Remove all non-digit characters
if (value.length > 0) {
if (value.length <= 3) {
value = `(${value}`;
} else if (value.length <= 6) {
value = `(${value.substring(0, 3)})${value.substring(3)}`;
} else if (value.length <= 10) {
value = `(${value.substring(0, 3)})${value.substring(3, 6)}-${value.substring(6)}`;
} else {
value = `(${value.substring(0, 3)})${value.substring(3, 6)}-${value.substring(6, 10)}`;
}
}
phoneInput.value = value;
});
phoneInput.addEventListener("keydown", function(event) {
if (event.key === "Backspace") {
let value = phoneInput.value;
// Remove formatting characters if at those positions
if (value.endsWith(") ") || value.endsWith("-")) {
phoneInput.value = value.slice(0, -1);
} else if (value.endsWith("(")) {
phoneInput.value = value.slice(0, -2); // Remove "( "
}
}
});
});
</script>
</body>
</html>
If this is the telephone field
<div class="field telephone required">
<label for="telephone" class="label">
<?= $escaper->escapeHtml(__('Phone Number')) ?>
</label>
<div class="control">
<input
type="text"
name="telephone"
id="telephone"
maxlength="13"
minlength="13"
title="<?= $escaper->escapeHtml(__('Phone Number')) ?>"
class="input-text validate-phone-13">
</div>
then the js code will be
<script type="text/javascript">
require([
"jquery"
], function ($) {
'use strict';
$(document).ready(function () {
$("#telephone").keypress(function () {
let x = $(this).val();
x = x.replace(/\D+/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1)$2-$3');
$(this).val(x);
});
$("#telephone").focusout(function () {
let x = $(this).val();
x = x.replace(/\D+/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1)$2-$3');
$(this).val(x);
});
});
});