2013-02-12 86 views
0

我正在使用jQuery來驗證表單中的某些字段,並且似乎在特定字段(#inputTel)中存在問題。使用jquery進行表單驗證的行爲不如預期

如果輸入的格式不正確,會在下面彈出一條錯誤消息,這很好,但問題是一旦輸入正確的格式,消息不會消失。

這是一個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

我強烈建議使用jQuery [Validation plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/)。 – Hari 2013-02-12 09:29:01

+0

我認爲這是正確的錯誤,當我把一個10位數的東西,然後它也去錯誤部分 – 2013-02-12 09:31:56

+0

它不是jQuery的,它的正則表達式這是搞東西 – 2013-02-12 09:37:20

回答

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/

+0

非常感謝您的幫助,讚賞.. – Richlewis 2013-02-12 10:56:49

+0

也作爲對正則表達式本身的修正,我注意到它已經被刪除了引號,爲什麼需要刪除? – Richlewis 2013-02-12 11:03:40

1

您也可以使用類似下面,少cubersome:

$(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(); 

      }); 

     });