jQuery验证文本字段取决于选择框 [英] JQuery Validating text field depending on select box

查看:48
本文介绍了jQuery验证文本字段取决于选择框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JQuery验证插件来验证输入字段.数字范围[range()]取决于选择框的值.For example when the select box is "A" the range should be between 1 and 10. But when its "B" it should be between 5 and 10 and so on.我确实尝试过读出选择框的值并调用一个函数来验证输入,并传递最小值.

I'm trying to validate a input field with the JQuery validation plugin. The numeric range [range()] depends on the value of a select box. For example when the select box is "A" the range should be between 1 and 10. But when its "B" it should be between 5 and 10 and so on. I did try this with reading out the value of of the select box and call a function to validate the input, passing the minumum value.

这有效,但是当您选择"A"并且您认为它应该是"B"时,它仍然会验证为"A".我当时在考虑依赖",但我只认为它适用于必需".

This works but when you select "A" and you think hmm it should be "B" it still validates as "A". I was thinking about 'depends' but I only think it works on 'required'.

$("#theSelectID").change(function () {
        var theValueOfSelected = $('#LeverancierID :selected').text();
        switch(theValueOfSelected){
        case "A":
            minval(1, "Null");
            break;
        case "B":
            minval(5, "PRCC");
            break;
            }
            function minval(theVal, theLev){
        $("#AddInkoop").validate({  
            rules: {
                Aantal: {
                    required: true,
                    range: [theVal, 999]
                }
            },
            messages: {
                Aantal:{
                    required:"required",
                    range: "give a number between "+ theVal +" and 999."
                }
            }
         });
    }

推荐答案

我认为您会倒退.设置验证规则,以便它使用反映选择框当前值的函数来计算最小值,而不是每次选择框更改时都更改验证设置.请注意,您可能需要更新一些描述性文字,以表明选择更改时可接受的范围.

I think you are going about it backwards. Instead of changing the validation set up every time the select box changes, set up the validation rule so that it calculates the minimum value using a function that reflects the current value of the select box. Note that you may want to update some descriptive text indicating what the acceptable range is when the select changes.

 $("#AddInkoop").validate({  
        rules: {
            Aantal: {
                required: true,
                range: function() { return [ $('#LeverancierID').val(), 999 ]; }
            }
        },
        messages: {
            Aantal:{
                required:"required",
                range: "the value is outside the acceptable range"
            }
        }
});

这篇关于jQuery验证文本字段取决于选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆