2017-05-03 76 views
1

我創建了一個jQuery自定義驗證這樣Jquery自定義驗證器 - 檢查一個值是否有效?

 var response; 
    $.validator.addMethod(
     "uniqueUserName", 
     function (value, element) { 

      $.ajax({ 
       type: "POST", 
       url: "/umbraco/surface/MemberShipSurface/ValidatePostCode", 
       data: JSON.stringify({ PostCode: value }), 
       contentType: "application/json; charset=utf-8", 
       success: function (msg) { 
        alert(msg.istrue); 
        response = msg.istrue; 

       } 
      }); 
      return response; 
     }, 

     "wrong postcode" 
    ); 
    $("#reg-form").validate({ 
    rules: { 
     day: { 
      required: true, 
      range: [01, 31] 
     }, 
     PostCode: { 
      required: true, 
      number: true, 
      maxlength: 4, 
      minlength: 4, 
      uniqueUserName: true 
     } 
    }, 

    errorElement: "span", 

    submitHandler: function (form) {  
    } 
}); 

如果從阿賈克斯輸出是事實,就意味着驗證是成功的,我們不需要顯示任何錯誤信息顯示其他錯誤信息。但是現在,我首先從表單上輸入了什麼價值,然後從第二次開始顯示驗證成功。任何人都可以指出我在這裏做錯了嗎?

+0

聲明這個'無功響應=假;' – vel

回答

1

remote-method可用,你可以使用它像,

rules: { 
    day: { 
     required: true, 
     range: [01, 31] 
    },    
    PostCode: { 
     required: true, 
     number: true, 
     maxlength: 4, 
     minlength: 4, 
     remote: { 
     url: "/umbraco/surface/MemberShipSurface/ValidatePostCode", 
     type: "post", 
     data: { 
      PostCode: function() { 
      return $("#PostCode").val(); 
      } 
     } 
     } 
    } 
} 

如果要使用自定義的方法,然後在$.ajax()調用中使用async=false

var response=false; 
$.ajax({ 
    type: "POST", 
    async:false,// now it will wait until you get response 
    url: "/umbraco/surface/MemberShipSurface/ValidatePostCode", 
    data: JSON.stringify({ PostCode: value }), 
    contentType: "application/json; charset=utf-8", 
    success: function (msg) { 
     response = msg.istrue; 
    } 
}); 
return response; 
+0

這個代碼不表示什麼都數據我進入你'msg.istrue'正在返回 – Athul

+0

什麼值的錯誤信息? –

1

嘗試。

var response= false; 
    $.validator.addMethod(
     "uniqueUserName", 
     function (value, element) { 

      $.ajax({ 
       type: "POST", 
       url: "/umbraco/surface/MemberShipSurface/ValidatePostCode", 
       data: JSON.stringify({ PostCode: value }), 
       contentType: "application/json; charset=utf-8", 
       success: function (msg) { 
        alert(msg.istrue); 
        response = msg.istrue === "true" ? true : false; 

       } 
      }); 
      return response; 
     }, 

     "wrong postcode" 
    ); 
    $("#reg-form").validate({ 
     rules: { 
      day: { 
       required: true, 
       range: [01, 31] 
      }, 
      PostCode: { 
       required: true, 
       number: true, 
       maxlength: 4, 
       minlength: 4, 
       uniqueUserName: true 
      } 
     }, 

     errorElement: "span", 

     submitHandler: function (form) {  
     } 
    }); 
+0

不工作。同樣的問題,我上面說過再次發生 – Athul

+0

whiat值msg.istrue? – vel

+0

如果數據是有效的然後是真的,如果數據是錯誤的假 – Athul