Jonathan M.
Jonathan M.

Reputation: 3

Knockout binding with custom extender and validation

I'm using KnockoutJS 3.2.0 along with the newest Knockout-Validation and mapping. The Controller send me a complex JSON object from Model. Many thinks work great. Now I got a first bigger Problem I cant solve myself until now. I got extender which transform my value to Euro-string. And my own (or Validations 'max') extender to check the the value. Can anyone tell me what kind of error I have made? I use my extender direct in HTML. I would not set the extender manually.

I tried to make a very simple example for you. Type 150 > show error > type 100 > should hide error.

I update the Code. Now error notification work fine. But the model is still valid.

    ko.validation.rules['maxval'] = {
    validator: function (val, otherVal) {
        var nbr ;
           if(ko.validation.utils.isNumber(val))
           {
               nbr = val;            
           }
           else
           {
               nbr=val.split('€')[0]
           }
        return nbr <= otherVal;
    },
    message: 'Number should greater than or equal to {0} €'
};
ko.extenders.euro = function (target, precision) {                
                var result = ko.dependentObservable({
                    read: function () {
                        //sample                       
                        if(target().toString().indexOf('€') != -1) {
                            return target() ;}
                        else{
                            return target() +" €";}
                    },
                    write: target
                }).extend({
                    notify: 'always'
                });
                result.raw = target;
                return result;
            }; 
ko.validation.registerExtenders();
var data = { num : 100};
var viewModel = ko.validatedObservable(ko.mapping.fromJS(data));
ko.applyBindings(viewModel);
label { display: block; margin-top: 5px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://raw.githubusercontent.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.js"></script>
<script src="https://raw.githubusercontent.com/Knockout-Contrib/Knockout-Validation/master/dist/knockout.validation.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<fieldset>
    <label>work: <input data-bind="value: num.extend({ euro : 2,maxval : 130})" /></label>
    <label>work: <input data-bind="value: num.extend({ maxval : 130})" /></label>
</fieldset>

 <div>
    <button type="button" data-bind='enable: isValid()'>Submit</button>
    <label>button still valid</label>
</div>

Thanks

Upvotes: 0

Views: 2152

Answers (1)

super cool
super cool

Reputation: 6045

Well you should notice here that onLoad your textbox value is not a number(100 €) and you are trying to compare against a number using max:130 gives you always false.

Using Custom validation we can deal this issue effectively

Custom Validation Rules :

ko.validation.rules['maxval'] = {
    validator: function (val, otherVal) {
        var nbr ;
        if(val) { 
        nbr=val.split('€')[0]
        }
        return nbr <= otherVal;
    },
    message: 'Number should greater than or equal to {0} €'
};

Note: The value '130' is the second arg ('otherVal') that is passed to the validator

Register rules Created:

ko.validation.registerExtenders();

View Model :

ko.extenders.euro = function (target, precision) {                
                var result = ko.dependentObservable({
                    read: function () {
                        //sample                       
                        if(target().toString().indexOf('€') != -1) {
                            return target() ;}
                        else{
                            return target() +" €";}
                    },
                    write: target
                }).extend({
                    notify: 'always'
                });
                result.raw = target;
                return result;
            }; 

var data = { num : 100};
var viewModel = ko.validatedObservable(ko.mapping.fromJS(data));
ko.applyBindings(viewModel);

Working fiddle here

For documentation on ko validation refer here

Upvotes: 1

Related Questions