CaptainChizni Ответов: 1

Форма все еще отправляется, даже если она недействительна


<form class="form-container" onsubmit="return false" autocomplete="off" novalidate>
             <fieldset><h4 class ="text-center font-weight-bold ">Personal Information</h4></fieldset>

             <!-- ALERT FOR DUPLICATE AND SUCCESS -->
        <div class="form-group col-12 container">
            <div class="alert" id="alertMessage" role="alert" hidden>
                 <h6 class="alert-heading" id="alertHeading"></h6>
                <p id="sampleParagraph" class="text-center"></p>
                <a href="#" id="hrefText"></a>
            </div>
        </div>


       <div class="form-row">
           <div class="form-group col-xs-12 col-md-4">
               <label for="inputEmail4">First Name</label>
               <input type="text" class="form-control" id="txtFirstname" placeholder="" pattern=".{3,}" title="3 characters minimum" aria-describedby="inputGroupPrepend" required>
               <div class="invalid-feedback">
                           Required Field.
                    </div>
           </div>

           <div class="form-group col-xs-12 col-md-4">
                <label for="inputPassword4">Middle Name</label>
               <input type="text" class="form-control" id="txtMiddlename" placeholder=""  aria-describedby="inputGroupPrepend" required>
               <div class="invalid-feedback">
                           Required Field.
                    </div>
           </div>
           <div class="form-group col-xs-12 col-md-4">
               <label for="inputEmail4">Last Name</label>
               <input type="text" class="form-control" id="txtLastname" placeholder="" pattern=".{3,}" title="3 characters minimum" aria-describedby="inputGroupPrepend" required>
               <div class="invalid-feedback">
                           Required Field.
                    </div>
           </div>
       </div>


       <div class ="form-row">
       <div class="form-group col-12 col-md-8">
           <label for="inputAddress">Address</label>
            <input type="text" class="form-control" id="txtaddress" placeholder=""  aria-describedby="inputGroupPrepend" required>
           <div class="invalid-feedback">
                           Required Field
           </div>
       </div>

       <div class="form-group col-12 col-md-4">
           <label for="inputAddress2">City</label>
           <input type="text" class="form-control" id="txtcity" placeholder="" aria-describedby="inputGroupPrepend" required>
           <div class="invalid-feedback">
                           Required Field
           </div>
       </div>
           </div>


       <div class="form-row">
           <div class="form-group col-12 col-md-4">
               <label for="inputEmail4">Birthdate</label>
               <input type="text" class="form-control" id="txtbirthday" placeholder="" onkeypress="return false;" required>
               <!--<label id ="lblerrorbd" class="text-center" style="color:red; font-size:smaller;"></label>-->
               <div class="invalid-feedback">
                           Required Field
               </div>
                   <div class="input-group-addon">
                       <span class="glyphicon glyphicon-calendar"></span>
                   </div>
           </div>

           <div class="form-group col-12 col-md-4">
                <label for="inputPassword4">Mobile Number</label>
               <input type="text" class="form-control" id="txtmobilenumber" maxlength="11" placeholder="" value="09" pattern=".{11,}" title="Please input correct mobile number" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32);" aria-describedby="inputGroupPrepend" required>
               <div class="invalid-feedback">
                           Invalid Number.
                    </div>
           </div>
           <div class="form-group col-12 col-md-4">
               <label for="inputEmail4">Phone Number</label>
               <input type="text" class="form-control" id="txtphonenumber" maxlength="7" placeholder="" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32);" aria-describedby="inputGroupPrepend">
           </div>
       </div>
       <h4 class ="text-center font-weight-bold">Account Information</h4>




           <div class="form-group col-12 col-md-8 center-block">
               <label for="inputEmail4">Email</label>
               <input type="email" class="form-control" id="txtemail" placeholder="" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" title="email must be in correct format" aria-describedby="inputGroupPrepend" required>
               <div class="invalid-feedback" id="emailRequired">
                           Required Field.
                    </div>
           </div>

           <div class="form-group col-12 col-md-8 center-block">
               <label for="inputEmail4">Password</label>
               <input type="password" class="form-control" id="txtpassword" placeholder="" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Password minimum of 8 characters" onchange='check_pass();' aria-describedby="inputGroupPrepend" required>
               <div class="invalid-feedback" id="passRequired">
                           Required Field
                    </div>
           </div>

           <div class="form-group col-12 col-md-8 center-block">
               <label for="inputEmail4">Confirm Password</label>
               <input type="password" class="form-control" id="txtconfirmpassword" placeholder="" pattern=".{8,}" title="Password minimum of 8 characters" style="margin:0px auto; display:block;" aria-describedby="inputGroupPrepend" required>
               <div class="invalid-feedback" id="confirmRequired">
                           Required Field.
               </div>
           </div>


    <div class="form-group col-md-4 center-block d-block">
        <div id="recaptcha" style="text-align:center;"></div>

        <input type="hidden" class="hiddenRecaptcha required float-sm-right" name="hiddenRecaptcha" id="hiddenRecaptcha">
        <div id="hiddenRecaptcha" class="g-recaptcha d-flex justify-content-center" data-sitekey="6Le895kUAAAAAI0mfIUn2BiPTkbc-1aD1zt7L6UL"></div>
        <label id="lblerror" class="d-flex justify-content-center" style="color: red; font-size: smaller;"></label>
    </div>

    <div class="form-row col-md-8 center-block d-block">
            <button type="button" class="btn btn-primary float-right mx-1" onclick="login();">Cancel</button>
            <button type="submit" onsubmit="return false" id="newRegistration" class="btn btn-primary float-right mx-1">Register</button>

    </div>

    <br class ="clearfix"/>
    <br class ="clearfix"/>
    <br class ="clearfix"/>
    <br class ="clearfix"/>
       </form>


Что я уже пробовал:

Вот мой 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('form-container');
        // Loop over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function (form) {
            form.addEventListener('submit', function (event) {
                debugger;
                
                $("#txtpassword").keydown(function () {
                    var value = $(this).val();
                    if (value.length == 0) {
                        $("#passRequired").html("Required Field");
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    else {
                        $("#passRequired").html("Password must contain 8 characters with numbers and letters with at least 1 upper case character.");
                        event.preventDefault();
                        event.stopPropagation();
                    }
                });

                $("#txtconfirmpassword").keydown(function () {
                    var password = $("#txtpassword");
                    var confirmpassword = $(this).val();
                    if (confirmpassword.length == 0) {
                        $("#confirmRequired").html("Required Field");
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    else if (password != confirmpassword) {
                        $("#confirmRequired").html("Password doesn't match");
                        event.preventDefault();
                        event.stopPropagation();
                    }
                });

                $("#txtemail").keydown(function () {
                    var value = $(this).val();
                    if (value.length == 0) {
                        $("#emailRequired").html("Required Field");
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    else {
                        $("#emailRequired").html("Invalid Email");
                        event.preventDefault();
                        event.stopPropagation();
                    }
                });


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

1 Ответов

Рейтинг:
0

W∴ Balboos, GHB

Вот способ сохранить полный контроль над вашей формой:

Дайте вашей форме удостоверение личности.
Измените тип='submit' На 'button' и получите событие onclick.
Выполните проверку в целевой функции события onclick.

Если в какой-то момент проверка завершится неудачей (или установите флаг и дескриптор в конце для отчетов о множественных сбоях), просто вернитесь из функции - возможно, с фокусом, установленным на ошибочный ввод.

Если он проходит всю проверку - тогда id.submit() и вы в бизнесе.