0

我正在使用 jQuery 来验证表单中的某些字段,并且似乎特别是某个字段存在问题(#inputTel)。

如果输入了错误的格式,下面会弹出错误消息,这很好,但问题是一旦输入了正确的格式,消息并没有消失。

这是一个带有完整演示的jsFiddle 。

这是有问题的部分:

//Tel Validate
function is_valid_tel() {
    $this = $("#inputTel");
    var pattern = new RegExp("^\d{11}$");
    if (pattern.test($this.val())) { // valid
        if ($this.closest(".control-group").hasClass("error")) $this.closest(".control-group").removeClass("error");
        $this.siblings(".help-inline").css("display", "none");
        return true;
    } else { // error
        if (!$this.closest(".control-group").hasClass("error")) $this.closest(".control-group").addClass("error");
        $this.siblings(".help-inline").css("display", "block");
        return false;
    }
}

除了这个之外,其他所有字段都按预期工作。我的 jQuery 技能有限,所以我不确定如何解决这个问题。

4

2 回答 2

1

你也可以使用类似下面的东西,不那么繁琐:

$(function() {
            function validateTheForm() {
              var ok = true;
                $(".input-medium").each(function() {
                if($(this).val() == "") //use regex actually here
                { 
                  $(this).next().css("display","inline");
                  ok = false;
                }
                else {
                    $(this).next().css("display","none");
                }


            });
                return ok;
            }
            $(".btn").click(function() {
              $("form").submit(validateTheForm());
              $("form").submit();

            });

        });
于 2013-02-12T11:15:14.470 回答
1

您的代码中的问题:

替换var pattern = new RegExp("^\d{11}$");var pattern = new RegExp(/^\d{11}$/);

更新代码

//Tel Validate
function is_valid_tel() {
    $this = $("#inputTel");
    var pattern = new RegExp(/^\d{11}$/);// Update this line
    if (pattern.test($this.val())) { // valid
        if ($this.closest(".control-group").hasClass("error")) $this.closest(".control-group").removeClass("error");
        $this.siblings(".help-inline").css("display", "none");
        return true;
    } else { // error
        if (!$this.closest(".control-group").hasClass("error")) $this.closest(".control-group").addClass("error");
        $this.siblings(".help-inline").css("display", "block");
        return false;
    }
}

检查小提琴http://jsfiddle.net/rfg8H/

于 2013-02-12T09:30:44.510 回答