在提交之前将jquery验证应用于下拉列表选择

时间:2015-03-12 19:31:08

标签: jquery jquery-validate

如何将表单验证应用于下拉国家/地区代码列表?该列表必须保持<li>列表。在提交函数可以通过之前,它需要验证数字输入(它已经完成)以及国家/地区代码选择。当前实现验证了针对电话输入的国家/地区代码输入,但只要被选中,就不会自行验证。如何设置必须选择国家/地区代码的规则,并警告用户(突出显示下拉区域或文本输入下的消息)必须选择下拉列表?

HTML

<form id="phone">
<div style="text-align: center;">
    <div class="input-group">
        <div class="input-group-btn">'+ '
            <button id="label" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><span id="areaCodes">+1</span><span class="caret"></span>
            </button>
            <ul class="dropdown-menu" id="areaCodes" role="menu">
                <li><a href="#" id="1">+1</a>
                </li>
                <li><a href="#" id="44">+44</a>
                </li>
            </ul>
        </div>
        <input class="form-control phone" name="phone" aria-label="..." placeholder="Your phone number" type="text"> <span class="input-group-btn">
        <input class="btn btn-default submit" type="submit">SUBMIT</input>
        </span>
    </div>
</div>

的jQuery

$(document).ready(function () {

// Load dialog on page load
//$('#basic-modal-content').modal();

// Load dialog on click
$('#basic-modal .basic').click(function (e) {
    $('#basic-modal-content').modal();
    return false;
});

$("#1, #44").click(function (e) {
    $("#label").html("+" + $(this).attr("id") + " <span class='caret'></span>");
    var phone = $('input[name="phone"]');
    if ($(this).attr("id") == '1') {
        phone.rules('remove', 'phoneUK');
        phone.rules('add', {
            phoneUS: true
        });
    } else {
        phone.rules('remove', 'phoneUS');
        phone.rules('add', {
            phoneUK: true
        });
    }
});

$("#areaCodes li").click(function () {
    $("#label").text($($(this).find("a")).text())
    //removes isSelected class
    $("#areaCodes li a").removeClass("isSelected");
    //add isSlected Class to clicked element
    $($(this).find('a')).addClass("isSelected")
});

$('.phone').on('input', function (event) {
    this.value = this.value.replace(/[^0-9]/g, '');
});

$("#phone").validate({
    errorPlacement: function (error, element) {
        error.insertAfter($(element).parent('div'));
    },
    rules: {
        phone: {
            required: true,
            phoneUS: true
        }
    },
    messages: {
        phone: {
            phoneUS: "Please enter a valid US number",
            phoneUK: "Please enter a valid UK number"
        }
    },
    submitHandler: function (form) {
        $.ajax({
            url: '/textMessage/' + $("#areaCodes .isSelected").text() + $('input[name="phone"]').val(),
            method: "GET",
            success: function () {
                console.log(form);
            }
        });
        return false;
    }
});
});

当前版本:jsFiddle

2 个答案:

答案 0 :(得分:0)

$("#areaCodes li").click(function ()内添加blur函数到输入,因此它会尝试验证输入

$("#areaCodes li").click(function () {
    $("#label").text($($(this).find("a")).text())
    //removes isSelected class
    $("#areaCodes li a").removeClass("isSelected");
    //add isSlected Class to clicked element
    $($(this).find('a')).addClass("isSelected");

    //add this
    $('.phone').blur();
});

我在这里使用.phone,应该是ID #something,但要求你用手机添加id输入

fiddle here

更新的答案:

问题是,我认为,因为您的列表li不是输入,因此您无法使用“jQuery Validation”附加验证。另一个解决这个问题,我现在只想到2个, 首先检查提交功能是否有选择权, 要么 第二,在手机上添加自定义验证

规则:

rules: {
    phone: {
        listMustHaveValue: true,
        required: true,
        phoneUS: true

    },

验证器上的新方法:

 $.validator.addMethod(
        "listMustHaveValue", 
        function(value, element) {
            var liselected = $('#areaCodes .isSelected');
            return liselected .length > 0;
        },
        "List must have value"
    );

更新2:

不。 3, 正在更改 ul listselect option,因此您可以在那里进行验证,只需说明必需为真

答案 1 :(得分:0)

我添加了一个基于IP进行国家/地区检测的远程服务(https://www.wipmania.com/)。

$('.phoneNumber').on('input', function (event) {
  this.value = this.value.replace(/[^0-9]/g, '');
});
$("#phone").submit(function (e) {
e.preventDefault();

var that = this,
    country = $(this).find("#countryCodes").val(),
    phoneNumber = $(this).find(".phone").val(),
    callUrl = "/textMessage/" + country + phoneNumber,
    ukValid = new RegExp(/^[0-9]{10,11}$/),
    usValid = new RegExp(/^\d{10}$/);
console.log("phone# = ", phoneNumber);

function callService() {
    initialFormText();
    $.get(callUrl, function (data) {
        //console.log( "sent" );
    })
        .done(function () {
        //console.log( "success" );
    })
        .fail(function () {
        //console.log( "call error" );
    })
        .always(function () {
        //console.log( "finished" );
        $(that).addClass('hide').next('.success').addClass('active');
    });
}

function initialFormText() {
    $('.mb-35').html("Enter your phone number and we’ll send a link to your iPhone");
    $('.mb-35').css({
        'color': '#86888b'
    });
    }

    if ((country === "44") && (ukValid.test(phoneNumber))) {
        if ((phoneNumber.length > 10) && (phoneNumber[0] === "0")) {
            callService();
        } else if (phoneNumber.length < 11) {
            callService();
        } else {
            setTimeout(function () {
                $('.reload-form').click()
            }, 100);
            $(this).find('.mb-35').html("The number you have entered is incorrect format. Please enter correct phone number. ");
            $(this).find('.mb-35').css({
                'color': 'red'
            });
        }

    } else if (usValid.test(phoneNumber)) {
        callService();
    } else {
        setTimeout(function () {
            $('.reload-form').click()
        }, 100);
        $(this).find('.mb-35').html("The number you have entered is incorrect format. Please enter correct phone number. ");
        $(this).find('.mb-35').css({
            'color': 'red'
        });

        console.log("number is invalid");
    }
    return;
});


    //country detection==================
    $(document).ready(function () {
        $.ajax({
            url: "http://api.wipmania.com/jsonp?callback=?",
            dataType: "jsonp"
        }).done(function (data) {
            if (data) {

                if (data.address.continent === "North America") {

                    $($('.dropdown-menu').find('button').find('span').get(0)).html("US (+1)");
                    $('#countryCodes').val('1');

                    $('.dropdown-menu').each(function () {
                        $(this).find('.dropdown-menu').find('li').each(function () {
                            if ($(this).attr("data-value") === "1") {
                                $(this).addClass('disabled');
                            } else {
                                $(this).removeClass('disabled');
                            }
                        });
                    })

                } else if (data.address.continent === "Europe") {

                    $($('.dropdown-menu').find('button').find('span').get(0)).html("UK (+44)");
                    $('#countryCodes').val('44');

                    $('.dropdown-menu').each(function () {
                        $(this).find('.dropdown-menu').find('li').each(function () {
                            if ($(this).attr("data-value") === "44") {
                                $(this).addClass('disabled');
                            } else {
                                $(this).removeClass('disabled');
                            }
                        });
                    })

                } else {
                    $($('.dropdown-menu').find('button').find('span').get(0)).html("US   
         (+1)");
                    $('#countryCodes').val('1');

                    $('.dropdown-menu').each(function () {
                        $(this).find('.dropdown-menu').find('li').each(function () {
                            if ($(this).attr("data-value") === "1") {
                                $(this).addClass('disabled');
                            } else {
                                $(this).removeClass('disabled');
                            }
                        });
                    })
                }

            }

        });
    });