好的,我知道每个人的第一个想法是简单地创建另一个验证方法和消息.但这是交易.我们有一个表单,其中包含一个用作雇主姓名和公司名称的字段,具体取决于下拉列表中选择的内容.

我需要做的是当下拉列表显示他们拥有公司并且他们没有填写该字段然后它显示一条消息.如果他们不拥有公司并且它是空的,那么它会显示另一条消息.

我怎么做到这一点?这是使用最新版本的jQuery和Validate插件(http://jqueryvalidation.org/).

更新:
在选择下面的选定答案后,我向您展示了我最终得到的代码……

http://pastebin.com/iG3Z4BbJ

谢谢,享受!

代码详细信息:

/**
 * Reference: http://jqueryvalidation.org/rules
 */
$(document).ready(function() {
    var rules = {
        IncomeSource: 'required',NetIncome: {
            required: true,usDollar: true,minDollars: 1
        },//Begin - Fields that don't always show
        JobTitle: {
            //required: true,nameInput: true
        },Employer: {
            //required: true,EmployerPhone: {
            //required: true,phoneUS: true
        },BenefitSource: {
            //required: true,//SemiMonthlySpecifics: 'required',//Select one when Semi-Monthly or Monthly are selected
        //End - Fields that don't always show
        PayFrequency: 'required',LastPayDate: {
            required: true,pastDate: true,date: true
        },NextPayDate: {
            required: true,futureDate: true,DirectDeposit: 'required',EmploymentLength: 'required',ActiveMilitary: 'required',RoutingNumber: {
            required: true,digits: true,rangelength: [9,9]
        },AccountNumber: {
            required: true,rangelength: [4,17]
        },AccountType: 'required'
    };

    //And field specific (and even validation type specific) error messages
    var messages = {
        IncomeSource: ss.i18n._t('IncomeSourcerequiredError'),NetIncome: {
            required: ss.i18n._t('NetIncomerequiredError')
        },//Begin - Fields that don't always show
        JobTitle: {
            required: ss.i18n._t('JobTitlerequiredError')
        },Employer: {
            required: ss.i18n._t('EmployerrequiredError')
        },EmployerPhone: {
            required: ss.i18n._t('EmployerPhonerequiredError')
        },BenefitSource: {
            required: ss.i18n._t('BenefitSourcerequiredError')
        },SemiMonthlySpecifics: ss.i18n._t('SemiMonthlySpecificsrequiredError'),//Select one when Semi-Monthly or Monthly are selected
        //End - Fields that don't always show
        PayFrequency: ss.i18n._t('PayFrequencyrequiredError'),LastPayDate: {
            required: ss.i18n._t('LastPayDaterequiredError')
        },NextPayDate: {
            required: ss.i18n._t('NextPayDaterequiredError')
        },DirectDeposit: ss.i18n._t('DirectDepositrequiredError'),EmploymentLength: ss.i18n._t('EmploymentLengthrequiredError'),ActiveMilitary: ss.i18n._t('ActiveMilitaryrequiredError'),RoutingNumber: {
            required: ss.i18n._t('RoutingNumberrequiredError')
        },AccountNumber: {
            required: ss.i18n._t('AccountNumberrequiredError')
        },AccountType: ss.i18n._t('AccountTyperequiredError')
    };

    $('#applicationForm').validate({
        //debug: true,rules: rules,messages: messages,errorElement: 'span',ignore: '.ignore',onfocusout: function( element,event ) {
            $(element).valid();
        },invalidHandler: function(event,validator) {
            kclHelpers.openErrorModal(event,validator);
        },errorPlacement: function(error,element) {
            var insertLocation = kclHelpers.getInsertLocation(element);
            error.appendTo( insertLocation );
        },success: function(label,element) {
            element = $(element);
            var insertLocation = kclHelpers.getInsertLocation(element);
            insertLocation.hide();
            kclHelpers.parentShowSuccess(element,'.control-group');
        },//Had to use this for show/hide of errors because error placement doesn't get called on every error.
        showErrors: function(errorMap,errorList) {
            if (this.numberOfInvalids() > 0) {
                //We want to make sure that we show/hide things appropriately on error
                $.each(errorList,function(index,item) {
                    var domElement = item['element'];
                    var message = item['message'];

                    var element = $(domElement);
                    var insertLocation = kclHelpers.getInsertLocation(element);
                    insertLocation.show();
                    kclHelpers.parentShowError(element,'.control-group');
                });
            }

            this.defaultShowErrors();
        }
    });

    $('[rel=tooltip]').tooltip();

    // When the income source is changed,change the form respectively
    $('#IncomeSource').on('change',kclFinancialInfo.incomeSourceChanged);
    $('#PayFrequency').on('change',kclFinancialInfo.payFrequencyChanged);
});



/**
 * This is where we specify functions only for this form
 */
var kclFinancialInfo = function()
{
    return {
        incomeSourceChanged: function() {
            // Store and convert the income source to lowercase
            var val = $(this).val().toLocaleLowerCase();

            // Switch on the income source
            switch (val) {
                // Case for 'benefits'
                case 'benefits':
                    // Do not display the employment section
                    kclFinancialInfo.toggleEmploymentSection(false);

                    // display the benefit source section
                    kclFinancialInfo.toggleBenefitSource(true);
                    break;

                // Case for 'selfemployment'
                case 'selfemployment':
                    // display the benefit source section
                    kclFinancialInfo.toggleBenefitSource(false);

                    // display the employment section
                    kclFinancialInfo.toggleEmploymentSection(true,"Please enter your company's name");

                    // Call to update the labels for the employment section based on income source of 'selfemployment'
                    kclFinancialInfo.updateEmploymentSectionLabels('selfemployment');

                    // Hide the employer phone field
                    kclFinancialInfo.toggleEmployerPhone(true);
                    break;

                // Case for 'job' and default
                case 'job':
                default:
                    // Do not display the benefit source
                    kclFinancialInfo.toggleBenefitSource(false);

                    // display the employment section
                    kclFinancialInfo.toggleEmploymentSection(true,"Please enter your employer's name");

                    // Call to update the labels for the employment section based on income source of 'job'
                    kclFinancialInfo.updateEmploymentSectionLabels('job');

                    // Do not hide the employer phone field
                    kclFinancialInfo.toggleEmployerPhone(false);
                    break;
            }
        },payFrequencyChanged: function() {
            var val = $(this).val().toLocaleLowerCase();

            switch (val) {
                case 'semi_monthly':
                    // display the Specific SemiMonthly section
                    kclFinancialInfo.toggleSpecificSemiMonthly(true,val);

                case 'monthly':
                    // display the Specific SemiMonthly section BUT change the labels
                    kclFinancialInfo.toggleSpecificSemiMonthly(true,val);

                    break;
                default:
                    // Do not display the Specific SemiMonthly section
                    kclFinancialInfo.toggleSpecificSemiMonthly(false);
                    break;
            }
        },toggleSpecificSemiMonthly: function(show,value) {
            if (show) {
                if (value == 'semimonthly') {
                    $('#specifics-label-for-SemiMonthlySpecifics_day').text(ss.i18n._t('FINANCIAL_informatION_PAGE.SEMI_MONTHLY_SPECIFICS_DAY'));
                    $('#specifics-label-for-SemiMonthlySpecifics_date').text(ss.i18n._t('FINANCIAL_informatION_PAGE.SEMI_MONTHLY_SPECIFICS_DATE'));
                }
                else {
                    $('#specifics-label-for-SemiMonthlySpecifics_day').text(ss.i18n._t('FINANCIAL_informatION_PAGE.MONTHLY_SPECIFICS_DAY'));
                    $('#specifics-label-for-SemiMonthlySpecifics_date').text(ss.i18n._t('FINANCIAL_informatION_PAGE.MONTHLY_SPECIFICS_DATE'));
                }

                $('#semi-monthly-specifics').show().removeClass('hidden');
                $('input[name="SemiMonthlySpecifics"]').rules('add','required');
            }
            else {
                kclHelpers.hideMessage('SemiMonthlySpecifics');
                $('#semi-monthly-specifics').hide().addClass('hidden');
                $('input[name="SemiMonthlySpecifics"]').rules('remove','required');
            }
        },toggleEmployerPhone: function(hide) {
            // If you want to hide the employer phone field
            if (hide) {
                // Hide the employer phone
                $('#employer_phone').hide().addClass('hidden');
                $('employer_phone').rules('remove','required');
            }
            // Else (you don't want to hide the employer phone field)
            else {
                // display the employer phone field
                $('#employer_phone').show().removeClass('hidden');
                $('employer_phone').rules('add',toggleBenefitSource: function(show) {
            // If you want to show the benefit sources section
            if (show) {
                // Show the benefit source section
                $('#benefit_source').show().removeClass('hidden');

                // Since the benefit source section is Now visible,make it required
                $('#BenefitSource').rules('add','required');

                /**
                 * Hide the WorkPhone validation message if its displayed (it remains on the screen if the user
                 * selects benefits)
                 */
                kclHelpers.hideMessage('WorkPhone');
            }
            // Else (you don't want to show the benefit source section,display the default employment section)
            else {
                // Hide the benefit source section
                $('#benefit_source').hide().addClass('hidden');

                // Since the benefit source is Now hidden,it is no longer required
                $('#BenefitSource').rules('remove',toggleEmploymentSection: function(show,employerMessage = '') {
            // If you want to show the employment section
            if (show) {
                // Show the employment section
                $('#employment_section').show();
                $('#JobTitle').rules('add','required');
                $('#Employer').rules('add',{
                    required: true,messages: {
                        required: employerMessage
                    }
                });
                $('#EmployerPhone').rules('add','required');
            }
            // Else (you don't want to show the employment section)
            else {
                // Hide the employment section
                $('#employment_section').hide();
                $('#JobTitle').rules('remove','required');
                $('#Employer').rules('remove','required');
                $('#EmployerPhone').rules('remove',updateEmploymentSectionLabels: function(source) {
            // Switch on the income source (Now lowercase)
            switch (source.toLocaleLowerCase()) {
                // Case for 'job'
                case 'job':
                    /**
                     * Make sure the job title and employer labels are correct (this is needed in case the labels
                     * need to be changed back to default
                     */
                    $('#JobTitle_label').text(ss.i18n._t('FINANCIAL_informatION_PAGE.JOB_TITLE'));
                    $('#Employer_label').text(ss.i18n._t('FINANCIAL_informatION_PAGE.EMPLOYER'));
                    $('#Employer').attr('placeholder','Enter Employer Name');

                    break;
                // Case for 'selfemployment'
                case 'selfemployment':
                    // Change the employer label to correspond to self employment (Employer -> Your Company Name)
                    $('#Employer_label').text(ss.i18n._t('FINANCIAL_informatION_PAGE.SELF_EMPLOYER'));
                    $('#Employer').attr('placeholder','Enter Company Name');
                    break;
            }
        }
    }
}();


var kclHelpers = function()
{
    var firstErrorID = '';
    var errorCount = 0;

    return {
        //Expects jQuery element
        getInsertLocation: function(element) {
            var fieldName = element.attr('name');

            if (fieldName == 'Reference_1[Relationship]') {
                fieldName = 'Reference_1-Relationship';
            }
            else if (fieldName == 'Reference_2[Relationship]') {
                fieldName = 'Reference_2-Relationship';
            }

            var insertTo = "#" + fieldName + "-error";
            return $(insertTo);
        },//Expects jQuery element and a selector string
        parentShowError: function(element,parentSelector) {
            var parentElem = element.parents(parentSelector);

            if (!parentElem.hasClass('has-error')) {
                parentElem.addClass('has-error');
            }

            parentElem.removeClass('has-success');
        },//Expects jQuery element and a selector string
        parentShowSuccess: function(element,parentSelector) {
            var parentElem = element.parents(parentSelector);

            if (!parentElem.hasClass('has-success')) {
                parentElem.addClass('has-success');
            }

            parentElem.removeClass('has-error');
        },hideMessage: function(fieldName) {
            if (fieldName == 'CreatePassword') {
                // Clear the Create-Password error message as well as the Confirm-Password error message
                $('#ConfirmPassword-error').hide();
            }

            if (fieldName == 'CellPhone') {
                // Clear the Cell-Phone error message as well as the Home-Phone error message
                $('#HomePhone-error').hide();
            }

            /**
             * Find the id in the form styling file corresponding to field we wish to "clear"
             * And set its "display" value to "none",effectively deleting it
             * This is for the desktop version
             */
            $("#" + fieldName + "-error").hide();
        },openErrorModal: function(event,validator) {
            var errorCnt = validator.numberOfInvalids();
            var errors = '';
            var hasSetErrorID = false;
            kclHelpers.errorCount = errorCnt;

            if (errorCnt) {
                var message = "";

                for (var i in validator.errorMap) {
                    if (!hasSetErrorID) {
                        hasSetErrorID = true;
                        kclHelpers.firstErrorID = i;
                    }

                    var str = i;
                    var label = '';

                    if (i == 'AgreeTerms') {
                        label = 'Website terms';
                    }
                    else if (i == 'ContactTerms') {
                        label = 'Contact terms';
                    }
                    else if (i == 'HomePhone') {
                        label = 'Home Phone';
                    }
                    else if (i == 'RoutingNumber') {
                        label = 'Routing Number';
                    }
                    else if (i == 'AccountNumber') {
                        label = 'Account Number';
                    }
                    else if (i == 'SemiMonthlySpecifics') {
                        label = 'Pay Frequency Specifics';
                    }
                    else if (/Reference_1/i.test(str)) {
                        label = 'Reference 1 ' + $("label[for='" + i + "']").text();
                    }
                    else if (/Reference_2/i.test(str)) {
                        label = 'Reference 2 ' + $("label[for='" + i + "']").text();
                    }
                    else {
                        label = $("label[for='" + i + "']").text();
                    }

                    errors += '<li>' + label + ': ' + validator.errorMap[i] + '</li>';
                }

                message += '<ol>' + errors + '</ol>';

                $('#form-error-modal .modal-body .error-count').text(errorCnt);
                $('#form-error-modal ul.error-list').html(message);
                $('#form-error-modal').modal('show');
            }
        }
    }
}();

解决方法

使用 the .rules('add') method动态更改选择更改时的消息.然后使用 the .valid() method在字段上触发新测试,以便立即更新消息.
$(document).ready(function () {

    $('#myform').validate({
        rules: {
            type: {
                required: true
            },theName: {
                required: true
            }
        }
    });

    $('select[name="type"]').on('change',function () {
        var theMessage,theType = $(this).val();
        if (theType == 'employer') {
            theMessage = "required Message 1";
        } else if (theType == 'company') {
            theMessage = "required Message 2";
        } else {
            theMessage = "This field is required.";
        }
        // dynamically change the message
        $('input[name="theName"]').rules('add',{
            messages: {
                required: theMessage
            }
        });
        // trigger immediate validation to update message
        $('input[name="theName"]').valid();        
    });

});

工作演示:http://jsfiddle.net/CLFY9/

javascript – jQuery Validate插件 – 如何根据各种条件显示不同的错误消息的更多相关文章

  1. HTML5实现直播间评论滚动效果的代码

    这篇文章主要介绍了HTML5实现直播间评论滚动效果的代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  2. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. 前端监听websocket消息并实时弹出(实例代码)

    这篇文章主要介绍了前端监听websocket消息并实时弹出,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  4. HTML5之消息通知的使用(Web Notification)

    通知可以说是web中比较常见且重要的功能,私信、在线提问、或者一些在线即时通讯工具我们总是希望第一时间知道对方有了新的反馈。本篇文章主要介绍了HTML5之消息通知的使用(Web Notification),感兴趣的小伙伴们可以参考一下

  5. HTML5中的Web Notification桌面通知功能的实现方法

    这篇文章主要介绍了HTML5中的Web Notification桌面通知功能的实现方法,需要的朋友可以参考下

  6. HTML5仿微信聊天界面、微信朋友圈实例代码

    小编最近开发一个基于html5开发的一个微信聊天前端界面,功能很全面,下面小编给大家分享实例代码,需要的朋友参考下

  7. 使用layui实现左侧菜单栏及动态操作tab项的方法

    这篇文章主要介绍了使用layui实现左侧菜单栏及动态操作tab项的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  8. HTML5的postMessage的使用手册

    HTML5提出了一个新的用来跨域传值的方法,即postMessage,这篇文章主要介绍了HTML5的postMessage的使用手册的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  9. ios – Testflight无法安装应用程序

    我有几个测试人员注册了testflight并连接了他们的设备……他们有不同的ios型号……但是所有这些都有同样的问题.当他们从“safari”或“testflight”应用程序本身单击应用程序的安装按钮时……达到约90%并出现错误消息…

  10. xcode找不到匹配的配置文件

    我有一个AdhociOS应用程序,它给了我“在xcode6中找不到匹配的配置文件”,我创建了一个Adhoc配置文件,下载它,双击它并在General–Identity下选择了一个团队.但我接着得到了那条消息,并尝试使用“修复问题”按钮没有帮助.在构建设置–供应配置文件–发布我有“自动”.任何人都可以帮助我,我完全迷失了……

随机推荐

  1. jquery-plugins – 是否可以使用猫头鹰旋转木马实现循环/无限轮播?

    我正在使用猫头鹰旋转木马,它的工作完美,除了它不支持循环/无限滚动.我没有搜索google和stackoverflow的想法,没有运气.有没有人在猫头鹰旋转木马上实现圆形/无限滚动?

  2. jQuery动态输入字段焦点

    我想使用以下jQuery向我的页面动态添加一个输入字段:在这样做之后,我希望输入字段具有闪烁的文本光标的焦点,所以我想在创建后立即输入.有人可以告诉我我该怎么办?

  3. jquery – 为什么$(window).height()这样错了?

    我试图获取当前浏览器的视口高度,使用但我得到的价值观太低了.当视口高度高达850px时,我从height()获取大约350或400像素的值.这是怎么回事?

  4. jquery – 如果在此div之外和其他draggables内部(使用无效和有效的还原选项),则可拖动恢复

    例如这样但是由于明显的原因,这不行.我可以说这个吗?

  5. 创建一个jQueryUI 1.8按钮菜单

    现在jQueryUI1.8已经出来了,我正在浏览更新,并且遇到了新的Buttonwidget,特别是SplitButtonwithadropdown的演示之一.这个演示似乎表明Buttonwidget可以在这里创建一个下拉菜单.作为讨论的问题,我想知道使用这个新的Button小部件来创建一个下拉菜单有什么方法.干杯.解决方法您必须在按钮下方列出一个列表,方式类似于此处为自动完成提供的演示:http

  6. 灰色divs使用JQuery

    我试图使用这个代码:为了淡出一大堆名为MySelectorDiv的div,唯一的是,它只会淡出第一个而不是所有的div,为什么呢?

  7. 使用jQuery动态插入到列表中

    我有两个订单列表在彼此旁边.当我从一个列表中选出一个节点时,我想按照字母顺序插入到另一个列表中.抓住的是我想要把一个元素放在另一个列表中,而不刷新整个列表.奇怪的是,当我插入到右边的列表中,它工作正常,但是当我插入到左边的列表中时,顺序永远不会出来.我也尝试将所有内容读入数组,并将其排序在一起,以防止children()方法没有按照显示顺序返回任何东西,但是我仍然得到相同的结果.这是我的jQuer

  8. 没有回应MediaWiki API使用jQuery

    我试图从维基百科获取一些内容作为JSON:但我没有回应.如果我粘贴到浏览器的地址栏,就像我得到预期的内容.怎么了?解决方法您需要通过添加&callback=?来触发具有$.getJSON()的JSONP行为?在querystring上,像这样:Youcantestithere.没有使用JSONP,你正在击中same-originpolicy,阻止XmlHttpRequest获取任何数据.

  9. jQuery Ajax请求每30秒

    我有这段代码,但是有些人在我的网站上的值可能会改变.我需要每30秒钟更新一次#financediv.这可以做吗解决方法您可以将代码放在单独的函数中,如下所示:然后每30秒建立一个定时器调用该函数:祝你好运!总结以上是DEVMAX为你收集整理的jQueryAjax请求每30秒全部内容。如果觉得DEVMAX网站内容还不错,欢迎将DEVMAX网站推荐给好友。

  10. jquery – keypress事件在IE和Chrome中不工作,但在FF工作

    任何想法为什么会这样发生?我通常认为Chrome会更加宽容代码?这是我的按键键.我错过了什么吗?右图();和leftimage();是应该工作的功能,因为我在其他地方使用这些功能谢谢您的帮助!

返回
顶部