[英]Javascript: How to validate 4 relative fields to be greater than another
所以我有四個領域,需要一些邏輯。
邏輯必須如下所示,每個字段必須大於之前的字段。 假設[f1],[f2] ...為字段。
[f1] < [f2] < [f3] < [f4]
我遇到了一些瘋狂的情況,因為如果我遇到這樣的情況怎么辦:
[null] < [null] < [null] < [f4]
現在,我向[f4]字段添加一個值。 這意味着f3的最大值必須小於f4的值
現在我將值添加到字段f2
[null] < [f2] < [null] < [f4]
哎呀! 它也必須小於[f4],但是如果以后我輸入[f3]值,則它必須小於[f3]。 與另一邊一樣,“比……更大”
有沒有簡單的方法來實現此功能,而不是成千上萬個“ if”子句?
這就是我動態更改任何字段的驗證的方式:
$("form").removeData("validator");
$("#" + paramID).attr('data-val-range-max', valuemax)
$("#" + paramID).attr('data-val-range-min', valuemin)
$.validator.unobtrusive.parse(document);
編輯:
有效的終點是所有元素是否都具有值,有效的端點也像[5] <[null] <[null] <[10]
您可以使用Array.prototype.every,它會測試每個元素,如果沒有通過測試則會中斷。
function lessThan(array) { var a; array = array.filter(function (a) { // filter the array return a != null; // return only values != null }); a = array.shift(); // get the first element by shifting the array return array.every(function (b) { // return true if every element pass the test var r = a < b; // make the test a = b; // get the new comparing value for the next test return r; // return the test result }); } document.write(lessThan([42]) + '<br>'); // true (obviously!) document.write(lessThan([0, 1, 2, 3]) + '<br>'); // true document.write(lessThan([null, null, null, 4]) + '<br>'); // true document.write(lessThan([null, 3, null, 4]) + '<br>'); // true document.write(lessThan([0, 1, 0, 3]) + '<br>'); // false document.write(lessThan([5, null, null, 4]) + '<br>'); // false document.write(lessThan([null, null, null, null]) + '<br>'); // true
如果您願意,可以更換
var r = a < b;
a = b;
return r;
同
return [a < b, a = b][0];
它使用臨時數組存儲測試結果並將最后一個元素分配給a。
如果目的是查找數字是否按升序排列:
function lessThan(values){
if(values.length < 2) throw new Error("Can't make comparison");
var last = values[0],
result;
for(var i = 1; i < values.length; i++){
result = last < values[i];
last = values[i];
if(!result) break;
}
return result;
}
//lessThan([0,1,2,3]) === true;
//lessThan([0,1,0,3]) === false;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.