2010-10-06 152 views
0

我正在使用Jquery valdiation plugin驗證客戶端的表單。 我正在從XML文件中提取驗證錯誤消息。xml的jQuery驗證消息

$("#"+form).validate({ 
    errorLabelContainer: "#dialogError", //msg_error 
    wrapper: "li", 
    rules: { 
     txtInfringementID: { 
      required: true, 
      digits: true 
     }, 
     txtLicenceNumber: { 
      required: true    
     }, 
     txtDateOfOffence: { 
      date: true, 
      required: true 
     } 
    }, 
    messages: { 
     txtInfringementID: { 
      required:this.errorMessage("InfringementID","Required"), 
      digits: "Inf Id must be numeric only" 
     }, 
     txtDateOfOffence: { 
      required: "please enter date of offence", 
      date: "Date is not valid" 
     }, 
     txtLicenceNumber:this.errorMessage("LicenceNumber", "Required"), 
     txtSurname: this.errorMessage("DebtorSurname", "Required") 
    } 
)}; 

errorMessage函數如下。

this.errorMessage = function (Field, Rule) { 

    var message; 
    $.ajax({ 
     type: "GET", 
     url: "../../../ErrorMessages.xml", 
     dataType: "xml", 
     success: function (xml) { 

      $(xml).find("*[Name='" + Field + "']").each(function() { 
       message = $(this).find(Rule).text(); 
      }); 
     } 
    }); 

    return message; **//I am using a debugger here** 
} 

,我使用XML是

<?xml version="1.0" encoding="utf-8" ?> 
<ErrorMessage> 
    <Field Name="InfringementID"> 
     <Required>Infringement ID is required</Required> 
     <Digit>Infringement ID should be numeric only</Digit> 
    </Field> 
    <Field Name="LicenceNumber"> 
     <Required>License Number is Mandatory</Required> 
    </Field> 
    <Field Name="DebtorSurname"> 
     <Required>Debtor Surname is Mandatory</Required> 
    </Field> 
</ErrorMessage> 

但問題是,當我使用調試器,我正在從XML消息。如果我不使用調試器,我會得到默認消息「此字段是必需的」。我認爲,問題是this.errorMessage()是一個異步的請求,這個請求需要一些時間才能完成。我試圖用一些延遲setTimeout函數。但我不知道在哪裏放時間。歡迎任何思考過程。

我正在設置像這樣的超時。

required:setTimeout(this.errorMessage("InfringementID","Required"),10000), 

回答

0

errorMessage啓動ajax調用並直接返回之後,而不等待響應。因爲那message將一直null。 你的方法與setTimeout只推遲了errorMessage的呼叫。結果將與沒有它的結果相同。 使您的ajax調用同步,從而等待它的結果。

$.ajax({ 
    type: "GET", 
    async: false,  // wait for the response 
    url: "../../../ErrorMessages.xml", 
    dataType: "xml", 
    success: function (xml) { 
     $(xml).find("*[Name='" + Field + "']").each(function() { 
      message = $(this).find(Rule).text(); 
     }); 
    } 
}); 

編輯 我並不確切地知道你在問什麼,但我會試試看...... 因爲你的問題的最後一行的上面,或許下面部分將爲你做

required: function() { 
    setTimeout(this.errorMessage("InfringementID", "Required"), 10000); 
} 
+0

謝謝,我不能把一些延遲,當我回來的消息。 – 2010-10-06 06:18:46

+0

我編輯了我的答案。希望它適合你的問題。 – Andreas 2010-10-06 16:56:01