2011-11-11 83 views
0

我在我的應用程序中使用jQuery驗證。但現在我們打算在單獨的文件(ErrMsgs.js)中聲明所有錯誤消息變量,並使用這些變量代替JQuery驗證插件(jquery.validate.min.js)中的錯誤消息。包括Js與JQueryValidation

一些我如何需要包括ErrMsgs.js在jquery.validate.min.js文件文件,這樣我可以利用在ErrMsgs.js

聲明的變量的我在jquery.validate使用下面的腳本.min.js

loadJavaScriptFile("Scripts/ErrMsgs.js"); 

function loadJavaScriptFile(jspath) { 
    document.write('<script type="text/javascript" src="' + jspath + '"><\/script>'); 
} 

但我無法使用在ErrMsgs.js中聲明的變量。

請給我解決方案。

謝謝。

+1

這將幫助你 http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file –

+0

@KanishkaPanamaldeniya感謝快速回復。 Tats有用,但我需要在「jquery.validate.min.js」以外的其他文件中聲明變量,並且需要在「jquery.validate.min.js」文件中使用這些變量。 – sandeep

回答

1

您可以使用JavaScript加載器,如http://requirejs.org/http://www.andresvidal.com/jsl。如果您更喜歡jQuery,那麼我只是發現這個http://api.jquery.com/jQuery.getScript/,它使用jQuery ajax調用,但將結果解析爲成功腳本。

每一種允許您在成功執行自己的代碼,這樣你就可以將其連接到驗證的消息對象,或任何如下(jQuery的例子):

$.getScript("Scripts/ErrMsgs.js", function(data, textStatus){ 
    $.extend(jQuery.validator.messages, myCustomErrorMessages); 
}); 

如果你嘗試按照您當前的方式加載腳本,我不認爲瀏覽器會將該字符串解析爲JavaScript。

1

你可以簡單地把你的ErrMsgs.js文件中的以下內容:

$.extend(jQuery.validator.messages, { 
    required: "This field is required.", 
    remote: "Please fix this field.", 
    email: "Please enter a valid email address.", 
    url: "Please enter a valid URL.", 
    date: "Please enter a valid date.", 
    dateISO: "Please enter a valid date (ISO).", 
    number: "Please enter a valid number.", 
    digits: "Please enter only digits.", 
    creditcard: "Please enter a valid credit card number.", 
    equalTo: "Please enter the same value again.", 
    accept: "Please enter a value with a valid extension.", 
    maxlength: $.validator.format("Please enter no more than {0} characters."), 
    minlength: $.validator.format("Please enter at least {0} characters."), 
    rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."), 
    range: $.validator.format("Please enter a value between {0} and {1}."), 
    max: $.validator.format("Please enter a value less than or equal to {0}."), 
    min: $.validator.format("Please enter a value greater than or equal to {0}.") 
}); 

然後包括它像任何其他JavaScript文件:

<script type="text/javascript" src="ErrMsgs.js"></script> 

編輯:

基於這些變數的評論需要在另一個地方使用,也許下面的工作。

var msg1 = "This field is required.", 
    msg2 = "Please fix this field.", 

    // etc., etc. 

$.extend(jQuery.validator.messages, { 
    required: msg1, 
    remote: msg2, 

    // etc. etc. 

}); 

$.extend(jQuery.xyz.messages, { 
    required: msg1, 
    remote: msg2, 

    // etc. etc. 

}); 
+0

真的很有幫助,但我需要在除「jquery.validat.min.js」以外的其他文件中使用這些變量。 「ErrMsg.js」是一個將被2個js文件「jquery.validat.min.js」和「xyz.js」使用的文件。這可能嗎? – sandeep

+0

@sandeep,我不完全確定你要做什麼,但我編輯了我的答案,以顯示如何使用變量來定義每條消息。在使用相同變量的同時,您還可以使用[jQuery'$ .extend()'](http://api.jquery.com/jQuery.extend/)作爲其他函數的第二次。 – Sparky