Knockout validation - isValid() always true after value change

497 Views Asked by At

I have the following scenario:

function ViewModel(){

    var self = this;

    self.newQty = ko.observable().extend({        
        pattern: {
            message: "Wrong!",
            params: new RegExp("^[1-9][0-9]*(\\,\\d{1,2})?|0+\\,\\d{1,2}$")
        }
    });

    self.newQty.subscribe(function() {
        if(self.newQty.isValid())
            doStuff();
    })
}

newQty field is bound to an input element.

If I type "123" into the input box, isValid() evaluates to true, and if I type "asd" into the input box the isValid() evaluates to false.

The problem manifests itself when I change "123" to "123a". isValid() still evaluates to true.

My question is: is there a way to manualy force re-evaluation of the field newQty? I found some posts that sugest calling valueHasMutated() but I get Maximum call stack size exceeded error when I use it.

I use Knockout 2.3.0 and latest version of Knockout-validation plugin.

Thanks!

1

There are 1 best solutions below

2
On BEST ANSWER

The problem is that you're not escaping your alternation (|). If you add parenthesis it should work:

params: new RegExp("^([1-9][0-9]*(\\,\\d{1,2})?|0+\\,\\d{1,2})$")

You can test it in the browser console:

'1234a'.test(/^[1-9][0-9]*(\\,\\d{1,2})?|0+\\,\\d{1,2}$/) //returns true
'1234a'.test(/^([1-9][0-9]*(\\,\\d{1,2})?|0+\\,\\d{1,2})$/) //returns false