How to Automatically Format Phone Number with JavaScript

Posted on: March 13th, 2025
By: Tadeo Martinez

<input
              type="tel"
              name="user_phone"
              className="w-full p-3 pl-12 bg-white/30 text-white placeholder-gray-300 rounded-md"
              placeholder="Phone"
              required
              maxLength={14} // Prevents extra characters after formatting
              onChange={(e) => {
                let value = e.target.value.replace(/\D/g, ""); // Remove non-numeric characters
                if (value.length > 10) value = value.slice(0, 10); // Limit to 10 digits

                let formatted = "";
                if (value.length > 6) {
                  formatted = `(${value.slice(0, 3)}) ${value.slice(
                    3,
                    6
                  )}-${value.slice(6)}`;
                } else if (value.length > 3) {
                  formatted = `(${value.slice(0, 3)}) ${value.slice(3)}`;
                } else if (value.length > 0) {
                  formatted = `(${value}`;
                }

                e.target.value = formatted; // Update input value
              }}
            />
          </div>

Have any questions or comments? Write them below!


Leave a Reply

Your email address will not be published. Required fields are marked *