MikeW
MikeW

Reputation: 4809

using knockout validation how to do I validate exactly 5 digits and accept empty input

I'm using the knockout validate plugin and are running into a problem with this scenario

required is false but if there is input - must be exactly 5 digits

    var fileno = ko.observable()
        .extend({ pattern: {
             message: 'not exactly 5',
             params: '/\b\d{5}\b/g'
        }});

can anyone see the issue here?

Cheers!

Upvotes: 2

Views: 966

Answers (1)

nemesv
nemesv

Reputation: 139788

The validation plugin uses the string.match method internally which expects a regex object and if you pass in a string it converts it to an RegExp object with new RegExp(obj) but in this case you cannot use flags like g

So you need to pass in an already created regex object as the params

var fileno = ko.observable()
    .extend({ pattern: {
         message: 'not exactly 5',
         params: /\b\d{5}\b/g // or using new RegExp('\\b\\d{5}\\b', 'g')
    }});

Demo JSFiddle.

Upvotes: 2

Related Questions