GVKun编程网logo

javascript – jQuery Validate插件 – 按名称验证隐藏字段(jquery根据id隐藏元素)

6

在这篇文章中,我们将为您详细介绍javascript–jQueryValidate插件–按名称验证隐藏字段的内容,并且讨论关于jquery根据id隐藏元素的相关问题。此外,我们还会涉及一些关于Form

在这篇文章中,我们将为您详细介绍javascript – jQuery Validate插件 – 按名称验证隐藏字段的内容,并且讨论关于jquery根据id隐藏元素的相关问题。此外,我们还会涉及一些关于Form表单提交、自定义验证规则(validate插件)、google jQuery 引用文件,jQuery 引用地址集合(jquery 1.2.6至jquery1.5.2)、google jQuery 引用文件,jQuery 引用地址集合(jquery 1.2.6至jquery1.5.2)_jquery、javascript – jQuery Validate插件 – 如何根据各种条件显示不同的错误消息的知识,以帮助您更全面地了解这个主题。

本文目录一览:

javascript – jQuery Validate插件 – 按名称验证隐藏字段(jquery根据id隐藏元素)

javascript – jQuery Validate插件 – 按名称验证隐藏字段(jquery根据id隐藏元素)

主要问题

我是jQuery validate plugin的新手.我需要验证动态添加和删除的隐藏字段以及共享相同名称的字段.示例标记:

基本上,我需要知道是否存在名为hdnItemID的任何元素.如果它们存在,则验证应该成功,否则验证应该失败.

if($("input[name='hdnItemID']").length > 0) {
    //Form is valid
}
else {
    //Form is invalid
}

我看了几个似乎很接近的问题,但它们似乎不符合要求.有什么建议?

> jQuery Validate Plugin – How to create a simple custom rule?
> jquery validate – valid if hidden field has a value

次要问题

假设我问的是可能的,我如何指定验证消息的显示位置?目前,我在验证失败时按每个必需元素放置一个星号.我想继续这样做,但是通过提交按钮放置隐藏字段的验证消息.

最佳答案
使用插件的submitHandler事件来检查隐藏字段是否存在.然后,您可以有条件地提交表单.试试这个.

$(function() {
    $('#form1').validate({
       submitHandler: function(form) {
            if($("input[name='hdnItemID']").length > 0) {
                 //Form is valid
                 form.submit();
            }
            else {
                 //Form is invalid
                 alert('form data invalid');
            }
        }
    });
});

Form表单提交、自定义验证规则(validate插件)

Form表单提交、自定义验证规则(validate插件)

//插件下载: http://jqueryvalidation.org/

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html"
      xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="utf-8">
    <title>Form表单提交、自定义验证规则(validate插件)</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <script type="text/javascript" src="jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="jquery.validate.js"></script>
    <style type="text/css">
        *{
            margin: 0px;
            padding: 0px;
        }
    </style>
</head>
<body>
<form id="form1" action="index6.html" method="post" >
    <label for="frname">姓名:</label>
    <input id="frname" name="frname" type="text"/></br>

    <label for="email">email</label>
    <input id="email" name="email" type="email" /></br>
    <label for="password">密码</label>
    <input id="password" name="password" type="password" /> </br>

    <label for="confirm_password">确认密码</label>
    <input id="confirm_password" name="confirm_password" type="password"/></br>

    <label for="mobile">手机号码:</label><input type="text" id="mobile" name="user[mobile]"/></br>

    男:<input type="radio" id="gender_male" value="m" name="gender"/><br />
    女:<input type="radio" id="gender_female" value="f" name="gender" /><br />

    选项1<input type="checkbox" id="check_1" value="1" name="checkGroup"/><br />
    选项2<input type="checkbox" id="check_2" value="2" name="checkGroup" /><br />
    选项3<input type="checkbox" id="check_3" value="3" name="checkGroup" /><br />

    <select id="selectbox" name="selectbox">
        <option value=""></option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>

    <input type="submit" value="Submit" />
</form>
</body>

<script type="text/javascript">


    // 字符验证
    jQuery.validator.addMethod("frname",function(value,ele){
        return this.optional(ele)|| /^[\u0391-\uFFE5\w]+$/.test(value);
    });
    jQuery.validator.addMethod("mobile",function(value,ele){
        var se= /^[0-9]{8,11}$/i;
        return this.optional(ele)|| se.test(value);
    })

    //然后就可以使用这个规则
    $("#form1").validate({
        rules:{
            password:{    //password:input 的name
                required:true,
                minlength:5
            },
            confirm_password:{
                required:true,
                minlength:5,
                equalTo:"#password"
            },
            email:{
                required:true,
                email:true
            },
            frname:{
                required:true,
                rangelength:[5,10]
            },
            "user[mobile]":{
                required:true,
                mobile:true
            },
            gender:{
                required:true
            },
            checkGroup:{
                required:true,
                minlength:2
            },
            selectbox:{
                required:true
            }

        },
        messages:{
            password:{
                required:"没有填写密码",
                minlength: "密码不能小于{0}个字符"
            },
            confirm_password:{
                required:"没有填写密码",
                minlength: "确认密码不能小于{0}个字符",
                equalTo:"两次不一致"
            },
            email:{
                required:"输入email地址",
                email:"不是有效地址"
            },
            frname:{
                required:"用户名不能为空",
                rangelength:"5-10g个字符之间"
            },
            "user[mobile]":{
                required:"手机号码不能为空"
            },
            gender:{
                required:"必须选"

            },
            checkGroup:{
                required:"必须选",
                minlength:"至少选2项"
            },
            selectbox:{
                required:"必须选"
            }
        }

    })

</script>

</html>


google jQuery 引用文件,jQuery 引用地址集合(jquery 1.2.6至jquery1.5.2)

google jQuery 引用文件,jQuery 引用地址集合(jquery 1.2.6至jquery1.5.2)

1. 很多网站都是使用这种方式引入,客户的浏览器可能已经缓存过了 jquery。可以直接调用本地的,速度更快…
2. Google code 使用了 cdn 技术在很多地方有节点服务器,加载 jquery 时绝对不会比在你服务器上加载慢,本地服务器除外 : )
3. 可以节省服务器流量,降低服务器带宽压力

可以使用两种方式引用 google code 的jquery
一、引用 http://www.google.com/jsapi?key=Goolge 密钥
<script type="text/javascript">
google.load("jquery","1.4.2");
</script>

二、直接引用地址http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js


jQuery 1.2.6 引用文件
复制代码 代码如下:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>

google jQuery 1.3.2引用文件
复制代码 代码如下:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

google jQuery 1.4.2引用文件
复制代码 代码如下:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

google jQuery 1.5.2引用文件
复制代码 代码如下:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>

google jQuery 引用文件,jQuery 引用地址集合(jquery 1.2.6至jquery1.5.2)_jquery

google jQuery 引用文件,jQuery 引用地址集合(jquery 1.2.6至jquery1.5.2)_jquery

1. 很多网站都是使用这种方式引入,客户的浏览器可能已经缓存过了 jquery。可以直接调用本地的,速度更快…
2. Google code 使用了 cdn 技术在很多地方有节点服务器,加载 jquery 时绝对不会比在你服务器上加载慢,本地服务器除外 : )
3. 可以节省服务器流量,降低服务器带宽压力

可以使用两种方式引用 google code 的jquery
一、引用 http://www.google.com/jsapi?key=Goolge 密钥


二、直接引用地址http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js


jQuery 1.2.6 引用文件

复制代码 代码如下:



google jQuery 1.3.2引用文件
复制代码 代码如下:



google jQuery 1.4.2引用文件
复制代码 代码如下:



google jQuery 1.5.2引用文件
复制代码 代码如下:


javascript – jQuery Validate插件 – 如何根据各种条件显示不同的错误消息

javascript – jQuery Validate插件 – 如何根据各种条件显示不同的错误消息

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

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

我怎么做到这一点?这是使用最新版本的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插件 – 按名称验证隐藏字段jquery根据id隐藏元素的分享就到这里,谢谢您的阅读,如果想了解更多关于Form表单提交、自定义验证规则(validate插件)、google jQuery 引用文件,jQuery 引用地址集合(jquery 1.2.6至jquery1.5.2)、google jQuery 引用文件,jQuery 引用地址集合(jquery 1.2.6至jquery1.5.2)_jquery、javascript – jQuery Validate插件 – 如何根据各种条件显示不同的错误消息的相关信息,可以在本站进行搜索。

本文标签: