Knockout-Contrib / Knockout-Contrib/Knockout-Validation
parseRule function to allow creating custom extenders
- Dominant language
- JavaScript
- Stars
- 1k
- Forks
- 366
- PR merge metrics
- No merged PRs in 30d
Description
I want to be able to create my own extenders (e.g. 'date') that adds validation rules.
Currently to do this I would be required to call `knockout.validation.addRule` which means duplicating all the logic from `knockout.validation.addExtender` to handle parsing the rule.
I think a new method should be added, `knockout.validation.parseRule(name, params)`. The `addExtender` method would become `kv.addRule(observable, kv.parseRule(ruleName, params))`
As a workaround I'm currently using
``` javascript
(function() {
ko.validation.addExtender('date');
var base = ko.extenders['date'];
ko.extenders['date'] = function(observable, params) {
observable.iso = ko.pureComputed(formatISODate, observable);
base(observable, params);
}
});
```
With `parseRule` this could be changed to
``` javascript
(function() {
ko.extenders['date'] = function(observable, params) {
observable.iso = ko.pureComputed(formatISODate, observable);
ko.validation.addRule(observable, ko.validation.parseRule('date', params));
}
```
---
I did consider adding an `init` option to the validation rules that would be called when setting up the extender but I discounted that option for 4 reasons.
1. `init` isn't really part of the rule, it's part of the extender, so the method doesn't make sense.
2. `init` is misleading if the rule has no registered extender (it would never be called).
3. `init` is less flexible, you might want your extender to take custom parameters, where the validation parameters is a nested property (perhaps only conditionally adding the validation).
4. I feel this scenario while useful to support is not common. Having a dedicated `init` method to support it would be unnecessary if there was a simple `parseRule` function.
Contributor guide
Research direction
Start by reading the existing knockout.validation.addExtender and knockout.validation.addRule implementations, then compare them with the custom date extender example in the issue. Determine the expected parseRule return value and how addExtender should use it. Done means custom extenders can call parseRule without duplicating rule-parsing logic, with tests covering the new API and existing behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- frontend
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100