随用户进度验证表单(不仅在提交时)

时间:2018-10-17 12:15:55

标签: javascript jquery html5

我正在为我的申请制作注册表,并希望能够验证变更字段。例如,我希望能够在单击“提交”之前立即验证密码的复杂性。在下面的代码中,这仅在单击提交后才会发生。

我想为email字段做类似的事情,但是我似乎无法弄清楚如何在不验证整个表单的情况下对单个元素执行此操作。

我的HTML表单:

<form class="needs-validation" id="registration-form" novalidate>
    <div class="row">
        <div class="col-md mb-3 mx-auto">
            <label for="firstName">First name</label>
            <input type="text" class="form-control" id="fname" placeholder="" value="" required>
                <div class="invalid-feedback">
                  Required.
                </div>
        </div>
        <div class="col-md mb-3 mx-auto">
            <label for="lastName">Last name</label>
            <input type="text" class="form-control" id="lname" placeholder="" value="" required>
            <div class="invalid-feedback">
              Required.
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md mb-3 mx-auto">
            <label for="email">Email</label>
            <input type="email" class="form-control" id="email" placeholder="you@example.com" required>
            <div class="invalid-feedback">
                Email required.
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md mb-3 mx-auto">
            <label for="password">Create a password</label>
            <input type="password" class="form-control" id="password" pattern="(?=.*)\S{6,}" required>
            <div class="invalid-feedback">
                Please enter a valid password for your account. Password must be at least 6 characters in length.
            </div>
        </div>
        <div class="col-md mb-3 mx-auto">
            <label for="confirm-password">Confirm password</label>
            <input type="password" class="form-control" id="confirm-password" required>
            <div id="confirm-password-invalid-feedback" class="invalid-feedback">
                Please confirm your password.
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md mb-3 mx-auto">
            <button class="btn btn-primary btn-lg btn-block" type="submit">Create My Account</button>
        </div>
    </div>
</form>

我的Javascript如下,validation.js

(function() {
'use strict';

///...

$("form").submit(function(e){
    //register();
    if ($("form")[0].checkValidity() === false) {
        console.log('validation failed');
        event.preventDefault();
        event.stopPropagation();
    }
    else {
        console.log('calling posting now');
        posting();
        event.preventDefault();            
    }
});

var forms = document.getElementsByClassName('needs-validation');
var password = document.getElementById('password'), confirm_password = document.getElementById('confirm-password');

function validatePassword() {
    if(password.value != confirm_password.value) {
        //there is no boolean var to set validity to invalid
        //password.setCustomValidity('invalid');
        confirm_password.setCustomValidity('invalid');

        if (confirm_password.value != '') {
            document.getElementById('confirm-password-invalid-feedback').textContent = 'The passwords do not match.';
        }
        else {
            document.getElementById('confirm-password-invalid-feedback').textContent = 'Confirm your password.';
        }

        event.preventDefault();
        event.stopPropagation();
    }
    else {
        password.setCustomValidity(''); //reset validity to valid

        if (password.validity.valid == false) {
            document.getElementById('confirm-password-invalid-feedback').textContent = 'Please confirm your password.';
        }
        else {
            confirm_password.setCustomValidity('');
        }
    }
}

window.addEventListener('load', function() {
    //fetch all the forms we want to apply custom Bootstrap validation styles to
    //loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
        form.addEventListener('submit', function(event) {
            validatePassword();

            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            }

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

    password.onchange = validatePassword;
    confirm_password.onkeyup = validatePassword;
}, false);
})();

3 个答案:

答案 0 :(得分:0)

在更改时调用函数

$('form').change(function() {
    // code
})


您也可以这样做:

$('form').keydown(function() {
    // code
})


这是直播。

答案 1 :(得分:0)

您可以尝试以下方法:

$("input.email").change(function(){
    // Add the verification logic for that particular input (validation function?)
});

答案 2 :(得分:0)

如果要在提交表单之前验证字段,则必须在表单更改时设置事件侦听器并处理其中的验证。例如,如果要验证密码,可以将密码验证功能放在表单更改功能中,如下所示:

trait JsonSupporter extends DefaultJsonProtocol with SprayJsonSupport with NullOptions {

  implicit val SourceIdFormat = jsonFormat2(SourceId)
  implicit val ArticlesFormat = jsonFormat8(Articles)
  implicit val GetNewsFromSingleSourceResponseFormat = jsonFormat3(GetNewsFromSingleSourceResponse)
}