淘汰赛最小/最大验证不起作用
Posted
技术标签:
【中文标题】淘汰赛最小/最大验证不起作用【英文标题】:Knockout min/max validation not working 【发布时间】:2018-09-16 13:29:23 【问题描述】:我正在使用我在 https://www.moonlightbytes.com/blog/useful-knockout-js-binding-handlers 找到的自定义绑定处理程序
将输入格式化为货币非常有效。但是,它也会阻止我的 Knockout 最小/最大验证工作。我需要最少 1 和最多 200。有人为什么会这样吗?
自定义绑定
function formatCurrency(symbol, value, precision)
return (value < 0 ? "-" : "") + symbol + Math.abs(value).toFixed(precision).replace(/(\d)(?=(\d3)+\.)/g, "$1,");
function rawNumber(val)
return Number(val.replace(/[^\d\.\-]/g, ""));
ko.bindingHandlers.currency =
symbol: ko.observable("$"),
init: function (element, valueAccessor, allBindingsAccessor)
//only inputs need this, text values don't write back
if ($(element).is("input") === true)
var underlyingObservable = valueAccessor(),
interceptor = ko.computed(
read: underlyingObservable,
write: function (value)
if (value === "")
underlyingObservable(null);
else
underlyingObservable(rawNumber(value));
);
ko.bindingHandlers.value.init(element, function ()
return interceptor;
, allBindingsAccessor);
,
update: function (element, valueAccessor, allBindingsAccessor)
var symbol = ko.unwrap(allBindingsAccessor().symbol !== undefined ? allBindingsAccessor().symbol : ko.bindingHandlers.currency.symbol),
value = ko.unwrap(valueAccessor());
if ($(element).is("input") === true)
//leave the boxes empty by default
value = value !== null && value !== undefined && value !== "" ? formatCurrency(symbol, parseFloat(value), 2) : "";
$(element).val(value);
else
//text based bindings its nice to see a 0 in place of nothing
value = value || 0;
$(element).text(formatCurrency(symbol, parseFloat(value), 2));
;
ViewModel 可观察
self.PriceAdvanced = ko.observable("").extend( required: true, min: 1, max: 200 );
HTML
<input class="form-control max225" type="text" id="PriceAdvanced" name="PriceAdvanced" data-bind="currency: PriceAdvanced" size="23" placeholder="$0.00" />
【问题讨论】:
【参考方案1】:找到答案here,效果很好:
首先,创建自定义绑定,如...
ko.bindingHandlers.yourBindingName =
init: function(element, valueAccessor, allBindings, viewModel, bindingContext)
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
,
update: function(element, valueAccessor, allBindings, viewModel, bindingContext)
// This will be called once when the binding is first applied to an element,
// and again whenever any observables/computeds that are accessed change
// Update the DOM element based on the supplied values here.
;
...然后使用敲除验证注册自定义绑定:
ko.validation.makeBindingHandlerValidatable('yourBindingName');
【讨论】:
以上是关于淘汰赛最小/最大验证不起作用的主要内容,如果未能解决你的问题,请参考以下文章
将 jquery 版本从 2.1 升级到 3 后,淘汰验证自定义规则不起作用