You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用intl-tel-input库在容器输出表单中不同格式的电话号码?

完整修正代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>电话号码验证输出</title>
    <!-- 引入intl-tel-input的CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/css/intlTelInput.min.css">
</head>
<body>
    <form id="phoneForm">
        <input type="tel" id="phoneInput" placeholder="请输入电话号码">
        <button type="submit">提交</button>
    </form>
    <div id="output" style="margin-top: 20px;"></div>

    <!-- 引入intl-tel-input的JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/intlTelInput.min.js"></script>
    <script>
        // 初始化电话号码输入框实例
        const input = document.getElementById('phoneInput');
        const iti = window.intlTelInput(input, {
            initialCountry: 'auto',
            geoIpLookup: function(callback) {
                callback('cn');
            },
            utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/utils.js' // 核心依赖,必须引入
        });

        // 监听表单提交事件
        const form = document.getElementById('phoneForm');
        const output = document.getElementById('output');

        form.addEventListener('submit', function(e) {
            // 阻止页面刷新(关键!否则看不到输出)
            e.preventDefault();

            // 获取各项所需信息
            const isValid = iti.isValidNumber();
            const rawLocal = iti.getNumber(intlTelInputUtils.numberFormat.RAW);
            const local = iti.getNumber(intlTelInputUtils.numberFormat.NATIONAL);
            const e164 = iti.getNumber(intlTelInputUtils.numberFormat.E164);
            const international = iti.getNumber(intlTelInputUtils.numberFormat.INTERNATIONAL);
            const countryCode = iti.getSelectedCountryData().dialCode;
            const countryAbbr = iti.getSelectedCountryData().iso2;

            // 渲染输出内容
            output.innerHTML = `
                <p>1. 验证状态(Valid: ${isValid})</p>
                <p>2. 原始本地号码(Raw local): ${rawLocal || '未输入有效号码'}</p>
                <p>3. 本地号码(Local): ${local || '未输入有效号码'}</p>
                <p>4. E164格式号码: ${e164 || '未输入有效号码'}</p>
                <p>5. 国际格式号码: ${international || '未输入有效号码'}</p>
                <p>6. 国家码: ${countryCode || '未选择'}</p>
                <p>7. 国家缩写: ${countryAbbr || '未选择'}</p>
            `;
        });
    </script>
</body>
</html>
关键问题修正点
  • 必须引入utils.js:这是intl-tel-input处理号码格式化、验证的核心依赖,缺了它大部分格式化API都会失效。
  • 阻止表单默认提交:表单提交默认会刷新页面,刚生成的输出会直接消失,一定要用e.preventDefault()拦截。
  • 正确调用库的API:先通过window.intlTelInput初始化输入框实例,再用实例的isValidNumber()、getNumber()、getSelectedCountryData()等方法获取数据。
  • 处理无效输入:如果用户没输入有效号码,要显示提示,避免输出undefined这类混乱内容。

内容的提问来源于stack exchange,提问作者rocksandfossils

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 00:00:10