【问题标题】:Safari is not acknowledging the "required" attribute. How to fix it?Safari 不承认“必需”属性。如何解决?
【发布时间】:2026-02-03 05:25:01
【问题描述】:
<form id="customerForm">
    <label>
        First Name:
        <input id="firstName" required />
    </label>
    <label>
        Social Security Number:
        <input id="ssn" required pattern="^d{3}-d{2}-d{4}$"
            title="Expected pattern is ###-##-####" />
    </label>
    <input type="submit" />
</form>

当我在 Chrome 中尝试该文档时,它会接受条件并按预期显示错误。

但是当我在 Safari 中尝试该文档时,它没有显示错误。

【问题讨论】:

    标签: html google-chrome safari required


    【解决方案1】:

    目前,Safari 不支持“必需”输入属性。 http://caniuse.com/#search=required

    要在 Safari 上使用 'required' 属性,您可以使用 'webshim'

    1 - 下载 webshim

    2 - 输入此代码:

    <head>
        <script src="js/jquery.js"></script>
    
        <script src="js-webshim/minified/polyfiller.js"></script> 
    
        <script> 
            webshim.activeLang('en');
            webshims.polyfill('forms');
            webshims.cfg.no$Switch = true;
        </script>
    </head>
    

    【讨论】:

    • 谢谢!我决定改用 CDN 中的它,你可以在这里找到一个缩小版:cdnjs.com/libraries/webshim
    • 谢谢,我完全忘记了 Webshim,它立即解决了问题。遗憾地发现两个重复的问题,原则上答案很好,但与您的解决方案不接近;现在标记他们,并希望能引导更多的人看到这个帖子/答案!
    • 我在自己的回答中提到了您的答案(甚至将您的代码示例复制为其他人的“kickstart”),我刚刚被问到“webshims.cfg.no$Switch”这一行是什么=真;'确实如此。你能给我解释一下吗? :)
    • webshim.activeLang('en');
    • @detoro84 设置您要使用的语言,如下所述:afarkas.github.io/webshim/demos/demos/…
    【解决方案2】:

    目前,Safari 不会针对用户未提供的表单字段中的必需值(也不会针对用户在表单字段中输入的无效值)发出任何错误消息。但是您可以通过使用 hacks 或 polyfill 来启用它。请参阅 HTML5 Form Validation Fallback (without a library) 了解启用它的轻量级 hack,并参阅 h5Validate 了解基于 jQuery 的 polyfill 插件。

    【讨论】:

    • Webshim 是一个不错的库,但如果您的目标是解决 OP,那么链接的“HTML5 表单验证后备”在大约 20 行代码中是完美的。
    【解决方案3】:

    Safari 10.1 and newer 中应提供所需的属性。

    【讨论】:

      最近更新 更多