使用Jquery进行表单验证的行为不符合预期

时间:2013-02-12 09:17:35

标签: javascript jquery validation

我正在使用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技能有限,所以我不确定如何解决这个问题。

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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();

            });

        });
相关问题