为自定义复选框显示HTML5验证消息

4
我的注册表单使用HTML5验证来验证必填字段是否已填写。
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <form action="https://www.salesforce.com" method="POST" id="signup">
                <div class="form-group">
                    <label for="first_name">First name</label>
                    <input id="first_name" maxlength="40" name="first_name" size="20" type="text" class="form-control" required>
                </div>
                <div class="checkbox">
                    <label>
                        <input id="tou" name="tou" type="checkbox" value="1" required="required"/>
                        I have read and agree to the terms of use.
                    </label>
                </div>
                <input type="submit" name="submit" class="btn">
            </form>
        </div>
    </div>
</div>

我使用CSS将默认复选框替换为自定义的.svg复选框。

input[type=checkbox] {
    display: inline-block;
    font-style: normal;
    font-weight: normal;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    visibility: hidden;
}

input[type=checkbox]:before {
    content: url(/static/img/unchecked.svg);
    visibility: visible;
}

input[type=checkbox]:checked:before {
    content: url(/static/img/checked.svg);
}

尽管HTML5验证适用于其他字段,但我无法使其适用于自定义复选框。 我尝试了jQuery validation with custom CSS checkbox中提供的方法,但没有成功。 有什么建议吗?


你为什么要展示CSS,如果你在使用jQuery验证方面遇到了困难呢? - Adam Buchanan Smith
你为什么要将required设置为属性呢?为什么不像在文本输入上设置required一样设置它呢? - macksol
@AdamBuchananSmith 我想展示一下我如何隐藏默认复选框,以防解决方案需要。 - Jacob Hughes
@macksol 很好的发现。设置 required 作为属性是没有必要的。 - Jacob Hughes
1个回答

4
默认的HTML5验证错误消息不可见,因为您使用以下方式隐藏它:
input[type=checkbox] {
    visibility: hidden;
}

可以尝试这样做:

input[type=checkbox] {
    opacity: 0;
}

Fiddle here: https://jsfiddle.net/xfosb27j/2/


感谢您的回答,这对我很有帮助,即使是多年后。 - steve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接