Use Jquery Validation Plugin to add real-time validations to my form

纵饮孤独 提交于 2019-12-20 07:14:16

问题


I want to validate my form in real-time (on input) using this jquery plugin : https://jqueryvalidation.org/rules/?

This is an example of my current validation function:

(function(ns, window, document, $, undefined) {

var $form;

ns.init= function(){

    $form = $('#formQA');

    $form.validate({
        rules : {
            QResponse : {
                required: function (element) {
                    if ($(element).is(":visible")) {
                        return true;
                    }
                    return false;
                } ,
                maxlength: 255,
                minlength: 2
            }
        }
    })
}
})(home.createNS('home.qa.validation', false), window, document, jQuery);

回答1:


By default, it validates on the keyup event. However, validation is "lazy", not "eager", which means that no validation happens until after the first click of submit. So you'll have to tweak some settings.

$form.validate({
    rules : {
        // rules
    },
    onfocusout: function(element) {
        this.element(element); // triggers validation
    },
    onkeyup: function(element, event) {
        this.element(element); // triggers validation
    }
});

Your code:

required: function (element) {
    if ($(element).is(":visible")) {
        return true;
    }
    return false;
}

You do not need to test for visibility. By default, the plugin will dynamically ignore any hidden field. Just set required to true and let the rest happen.



来源:https://stackoverflow.com/questions/45821997/use-jquery-validation-plugin-to-add-real-time-validations-to-my-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!