[英]set variable value to jquery message + jquery.validate
如何在消息中獲取var total
值,
我也嘗試聲明里面的函數,但它給出了未定義的變量
var total = '';
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
var fund_old = $("#current_fund").val();
var fund_new = $("#new_fund").val();
total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if (parseFloat(fund_new) <= parseFloat(total)) {
return true;
} else {
return false;
}
return true;
}, 'sry sktiman' + total + 'is remaining value');
結果我得到總值的空白值
根據jQuery.validator.addMethod()
的文檔,您可以使用jQuery.validator.format()
生成一個函數,該函數接收驗證方法的參數並返回一個字符串消息,因此創建一個忽略任何參數並返回的函數一個字符串應該工作:
var total = '';
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
var fund_old = $("#current_fund").val();
var fund_new = $("#new_fund").val();
total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if (parseFloat(fund_new) <= parseFloat(total)) {
return true;
} else {
return false;
}
return true;
}, function() {return 'sry sktiman' + total + 'is remaining value'});
編輯
這個解決方案的小提琴可以在這里找到(感謝Sparky提供的代碼)。
可以在消息內使用可選參數。
第三個參數,可選參數(你稱之為arg
)可以在你的代碼中表示為arg[0]
, arg[1]
等。
然后,相應的值可以在您的消息中用作{0}
, {1}
等。
在.addMethod()
外部進行計算,並使用arg
參數傳遞值。
$.validator.addMethod("valueNotEquals", function(value, element, arg){
var fund_old= $("#current_fund").val();
var fund_new =$("#new_fund").val();
// do this calculation where the rule is declared. See 'validate()'
//total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if(parseFloat(fund_new) <= parseFloat(total)){
return true;
} else {
return false;
}
return true;
},'sry sktiman {0} is remaining value');
由於您沒有顯示.validate()
或HTML標記,可能是這樣的......
$('#myform').validate({
rules: {
fund_old: {
// your rules
},
fund_new: {
valueNotEquals: function() {
return ($parseFloat(9999999999.999999) - parseFloat($("#current_fund").val()));
}
}
}
});
原始演示: http : //jsfiddle.net/eZm7x/
嘗試,
var total = '';
$.validator.addMethod("valueNotEquals", function(value, element, arg){
var fund_old= $("#current_fund").val();
var fund_new =$("#new_fund").val();
total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if(parseFloat(fund_new) <= parseFloat(total)){
return true;
}else{
return false;
}
return true;
},'sry sktiman'+ (parseFloat(9999999999.999999) - parseFloat($("#current_fund").val())) + 'is remaining value');
在addMethod文檔中說:“添加自定義驗證方法。它必須包含名稱(必須是合法的javascript標識符),基於javascript的函數和默認字符串消息。”
因此,您要為插件添加自定義驗證功能 ,而不是執行該功能。
嘗試使用自定義驗證設置字段並填寫該字段以運行自定義函數。 只是在這之后檢查total
的VAR值。
只需添加此行函數(){return'sry sktiman'+ total +'is remaining value'}作為您的第二個參數,您可以輕松使用此變量
var total = '';
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
//Your default code here
}, function() {return 'sry sktiman' + total + 'is remaining value'});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.