带有验证形式的单选/切换按钮

时间:2019-07-22 22:56:41

标签: javascript html twitter-bootstrap

我正在创建一个带有单选按钮组字段和选择使用切换按钮的简单表单。验证工作正常,除了这一项。

使用PHP / Laravel语言,但如果可能的话,希望使用JS(Vanilla)解决。这样做的目的是在前端提供更干净,更通用的代码。

HTML

<form class="needs-validation" novalidate>
<div class="form-row">

    <div class="col-md-4 mb-3">

        <label>Documento</label>            
        <div data-toggle="buttons">
            <div class="btn-group">
                <label class="btn btn-info btn-lg">
                    <input type="radio" name="type" value="CNH" class="sr-only" required>
                    CNH
                </label>
                <label class="btn btn-info btn-lg" style="margin-left: 5px;">
                    <input type="radio" name="type" value="CPF" class="sr-only" required>
                    CPF
                </label>
                <label class="btn btn-info btn-lg" style="margin-left: 5px;">
                    <input type="radio" name="type" value="ID" class="sr-only" required>
                    Identidade (R.G.)
                </label>
            </div>
        </div>
        <div class="invalid-feedback">Selecione o documento que será utilizado.</div>
    </div>

    <div class="col-md-4 mb-3">
        <label for="numberDocument">Número</label>
        <input type="text" class="form-control" id="numberDocument" required>
        <div class="invalid-feedback">
            Número não informado!
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <label for="clientName">Nome</label>
        <input type="text" class="form-control" id="clientName" required>
        <div class="invalid-feedback">
            Nome do cliente não informado!
        </div>
    </div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>

JS

<script type="text/javascript">

(function () {
    'use strict';
    window.addEventListener('load', function () {
        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.getElementsByClassName('needs-validation');
        // Loop over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function (form) {
            form.addEventListener('submit', function (event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

1 个答案:

答案 0 :(得分:0)

首先

<input type="radio" name="type" id="document" value="CNH" class="sr-only" required>

id =“ document”使用了三遍

Id属性只能声明一次

相关问题