Validate form with bootstrap (novalidate)

I have a problem validating a form with bootstrap novalidate.
Some form fields include the "required" tag and others do not.

To verify, I submit the form with no data and the ‘was-validated’ class makes all the fields validated, the ones with the "required" tag are marked in red and the others in green.

The idea is to specify which fields to validate instead of the entire form.

Could you help me please?

Form

<form id="Data" method="POST" class="needs-validation mt-0" novalidate>
    <div class="row mb-1">
        <div class="col-lg-12 ">
            <div class="form-group">
                <label class="d-block font-weight-semibold">Name: <span class="text-danger">*</span></label>
                <input type="text" id="name" name="Name" class="form-control" autocomplete="off" required>
            </div>
        </div> <!-- / col -->
    </div> <!-- / row-->
    <div class="row mb-1">
        <div class="col-lg-12 ">
            <div class="form-group">
                <label class="d-block font-weight-semibold">Lastname: <span class="text-danger">*</span></label>
                <input type="text" id="lastname" name="lastname" class="form-control" autocomplete="off" required>
            </div>
        </div> <!-- / col -->
    </div> <!-- / row-->
    <div class="row mb-1">
        <div class="col-lg-12 ">
            <div class="form-group">
                <label class="d-block font-weight-semibold">Street: <span class="text-danger">*</span></label>
                <input type="number" id="Street" name="Street" class="form-control">
            </div>
        </div> <!-- / col -->
    </div> <!-- / row-->
</form>

JS

<script type="text/javascript">
    $('#Data').on('submit', function(e){
        e.preventDefault();
        var form = document.getElementById('Data');
        if (!form.checkValidity()) {
            e.preventDefault();
            e.stopPropagation();
        }
        else {
            $.ajax({
                //url: "",
                type: $('#Data').attr('method'),
                data: $('#Data').serialize(),
                //dataType: 'json',
                beforeSend: function(){ },
                success:function(response) {
                    if (response.success == true) {
                    }
                    else {
                    }
                }
            })
        }
        $('#Data').addClass('was-validated');
    });
</script>

25 thoughts on “Validate form with bootstrap (novalidate)”

Leave a Comment