本文使用Bootstrap4.4.1版本。
在用Bootstrap进行表单验证时,需要给form添加class="needs-validation"和novalidate属性。

<form action="" class="needs-validation" novalidate>
    <div class="form-group row">
        <label for="title" class="col-md-2 col-sm-3 col-4 col-form-label text-right"><span class="text-danger">*</span> 商品名称</label>
        <div class="col-sm-8 col-8">
            <input type="text" class="form-control" id="title" name="title" placeholder="请输入" required>
            <div class="invalid-feedback">请输入商品名称</div>
        </div>
    </div>
    <div class="form-group row">
        <label for="subtitle" class="col-md-2 col-sm-3 col-4 col-form-label text-right"><span class="text-danger">*</span> 商品分类</label>
        <div class="col-sm-8 col-8">
            <select name="type" class="form-control" value="" id="type" required>
                <option value="">请选择</option>
                <option value="1">美容护肤</option>
                <option value="2">服饰鞋帽</option>
                <option value="3">电子产品</option>
                <option value="4">日用百货</option>
            </select>
            <div class="invalid-feedback">请选择商品分类</div>
        </div>
    </div>
    <div class="form-group row">
        <label for="title" class="col-md-2 col-sm-3 col-4 col-form-label text-right"><span class="text-danger">*</span> 商品信息</label>
        <div class="col-sm-8 col-8">
            <textarea class="form-control" name="info" cols="30" rows="10" required></textarea>
            <div class="invalid-feedback">请输入商品信息</div>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-sm-8 col-8 offset-md-2 offset-sm-3 offset-4">
            <button type="submit" class="btn btn-primary">确 定</button>
        </div>
    </div>
</form>

还有如下js代码:

$(function() {
    // bootstrap 表单验证
    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) {

            // 滚动到第一个验证失败的位置
            var invalidDom = $('.needs-validation .form-control:invalid');
            invalidDom[0].scrollIntoView(true);

            event.preventDefault();
            event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
})

如果需要验证后滚动到第一个失败的位置只需添加两行代码,invalidDom可根据自己项目做适当调整。

// 滚动到第一个验证失败的位置
var invalidDom = $('.needs-validation .form-control:invalid');
invalidDom[0].scrollIntoView(true);

望记
184 声望7 粉丝