在动态选择选项时使用jQuery验证表单

时间:2014-05-23 12:31:41

标签: javascript jquery html5

我是jQuery和JavaScript的新手。我想验证表单并检查每个下拉列表选择列表中的不同条件,并在每个条件上显示自定义错误。我怎样才能做到这一点?我曾经尝试过但每次都失败了。

这是我的HTML代码:

<select name="forwardTo" id="forwardTo" onchange="numberLineTo(this.value)">
    <option name="none" value="0">Select</option>
    <option name="MobileNo" value="3" id="MobileNo">Mobile Number</option>
    <option name="character" value="1">Character</option>
</select>
<input name="carrierAddress" type="text" id="carrierAddress">
<div style="margin-left:140px;"><input type="submit" name="submit" value="Submit" onclick="numberLineTo();"/></div>

这是我的脚本

function numberLineTo(){
    $("<span class='err'></span>").insertAfter("#carrierAddress");
    if($("#forwardTo").val() =='0'){
        $("#carrierAddress").unbind("keypress").hide();
        $('.err').empty();
        $('.err').html("Please Select any option");
    }

    if( $("#forwardTo").val() =='3')
    {
        $("#carrierAddress").show();
        $('.err').empty();

        $("#carrierAddress").bind("keypress",(function (e) {
            if(e.which == ""){
                $('.err').clear();
                $("#carrierAddress").show();
                $('.err').replaceWith("Please enter your phone number");
                return true;
            }
            //if the letter is not digit then display error and don't type anything
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                //display error message
                if(!isNaN(e.which)){
                    $('.err').empty();
                    $("#carrierAddress").show();
                    $('.err').empty().replaceWith("Please provide a valid phone number");
                    return true;

                }
                return false;
                }
            })
        );
    }

    if($("#forwardTo").val() =='1'){
        $("#carrierAddress").unbind("keypress");
        $("#carrierAddress").show();
        $('span').removeClass('.err');
    }
}

2 个答案:

答案 0 :(得分:1)

这是一个更好的版本:http://jsfiddle.net/Oliboy50/bbtVH/3/

HTML

<select name="forwardTo" id="forwardTo">
    <option value="0">Select</option>
    <option value="3" id="MobileNo">Mobile Number</option>
    <option value="1">Character</option>
</select>
<input name="carrierAddress" type="text" id="carrierAddress">
<span id="carrierAddress-error" class="err"></span>

<div style="margin-left:140px;">
    <input type="submit" name="submit" value="Submit" />
</div>

JS

$(document).ready(function () {
    // Best practices when using reccurent jQuery objects
    var $forwardTo = $("#forwardTo"),
        $carrierAddress = $("#carrierAddress"),
        $carrierAddressError = $('#carrierAddress-error');
    // Others "global" variables
    var reg = /^\d+$/;

    $forwardTo.on('change', function () {
        var $that = $(this);
        // You should do a "switch" instead of several "if" statements
        if ($that.val() == '0') {
            $carrierAddress.hide();
            $carrierAddressError.text("Please Select any option");
        }
        if ($that.val() == '3') {
            $carrierAddress.show();
            $carrierAddressError.text("");
        }
        if ($that.val() == '1') {
            $carrierAddress.show();
            $carrierAddressError.removeClass('err'); // why ? 
        }
    });

    // Use 'input' event instead of 'keypress' which doesn't understand copy/paste for example
    $carrierAddress.on('input', function () {
        var $that = $(this);
        // trim() remove spaces on each side of the string
        if ($that.val().trim() == "") {
            $carrierAddressError.text("Please enter your phone number");
        }
        //if the string doesn't contain only digits then display error
        else if (!reg.test($that.val().trim())) {
            $carrierAddressError.text("Please provide a valid phone number");
        }
        else{
            $carrierAddressError.text("");
        }
    });
});

顺便说一下,在盲目使用之前,你应该尝试通过阅读一些文档或教程来学习。

我知道jquery有一个名为'jquery.validate'的插件可以帮助你做这种事情......虽然我从来没用过它。

答案 1 :(得分:0)

你几乎在那里,但它可以清理和结构更好......

HTML(删除了内联javascript事件):

<select name="forwardTo" id="forwardTo">
    <option name="none" value="0" selected="selected" >Select</option>
    <option name="MobileNo" value="3" id="MobileNo">Mobile Number</option>
    <option name="character" value="1">Character</option>
</select>
<input name="carrierAddress" type="text" id="carrierAddress">
<div style="margin-left:140px;"><input type="submit" name="submit" value="Submit"/></div>

的JavaScript

$("#carrierAddress").after($("<span class='err'></span>"));

function numberLineTo(){
    var val = $("#forwardTo").val();
    $("#carrierAddress").hide();
    $('.err').empty();
    if(val == '0'){
        $('.err').html("Please Select any option");
    }
    if(val == '3')    {
        $("#carrierAddress").show();       
    }
};
numberLineTo();

$("#forwardTo").on("change",function(e){
    numberLineTo();
});

$("input[type=submit]").on("click",function(e){
    numberLineTo();
    alert("do something!");
});

$("#carrierAddress").on("keypress",function(e){
    $('.err').empty();
    if (e.keyCode === 13) {// 'enter' key
        return;
    }
    //if the letter is not digit then display error and don't type anything
   if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
       //display error message
       if(!isNaN(e.which)){
           $("#carrierAddress").show();
           $('.err').html("Please provide a valid phone number");
       }
   return false;
   }
});

以下是演示: http://jsfiddle.net/89qtN/