javascript - Knockout.js custom validation rule for logical OR for two input fields -
how can validate 2 input fields knockout.js? rule is: @ least 1 of input fields must filled in.
ko.validation.rules['or'] = { validator: function (val, otherval) { return (val || otherval); }, message: "you have fill in @ least 1 of 2 input fields!" }; ko.validation.registerextenders(); self.description = ko.observable().extend({ or: self.title }); self.title = ko.observable().extend({ or: self.description });
at moment: on init 1 of fields red , 1 green - should both red on start.
https://github.com/knockout-contrib/knockout-validation
self.title = ko.observable().extend({ or: self.description }); self.description = ko.observable().extend({ or: self.title });
title
valid description
not valid on start. when change code order to:
self.description = ko.observable().extend({ or: self.title }); self.title = ko.observable().extend({ or: self.description });
then opposite.
even example knockout contribution doesn't work me: https://github.com/knockout-contrib/knockout-validation/wiki/user-contributed-rules
ko.validation.rules['requiresoneof'] = { getvalue: function (o) { return (typeof o === 'function' ? o() : o); }, validator: function (val, fields) { var self = this; var = ko.utils.arrayfirst(fields, function (field) { var stringtrimregex = /^\s+|\s+$/g, testval; var val = self.getvalue(field); if (val === undefined || val === null) return !required; testval = val; if (typeof (val) == "string") { testval = val.replace(stringtrimregex, ''); } return ((testval + '').length > 0); }); return (anyone != null); }, message: 'one of these fields required' }; self.title = ko.observable(); self.description = ko.observable(); self.title.extend({requiresoneof: [self.title, self.description]}); self.description.extend({requiresoneof: [self.title, self.description]});
i found error. chicken-egg-problem.
at moment when gave title or description validation, not initialized yet. changed code , works:
//define validation rule: ko.validation.rules['or'] = { validator: function (val, params) { "use strict"; return (val !== "" && val !== undefined) || ( params.other() !== "" && params.other() !== undefined); }, message: "you have fill in @ least 1 of 2 input fields!" }; ko.validation.registerextenders(); //apply validation rule: self= this; self.description = ko.observable(); self.title = ko.observable(); self.title.extend({ or: { params: {other: self.description}, message: "please fill @ least 1 field!" } }); self.description.extend({ or: { params: {other: self.title}, message: "please fill @ least 1 field!" }});
Comments
Post a Comment