How to add a custom message to a pattern validation in ko validation
Asked Answered
C

1

8

Let's say I have:

self.UserName = ko.observable("").extend({ required: true }).extend({ pattern: '[\S]' });

I'm trying to do something like (I've tried a few variations):

self.UserName = ko.observable("").extend({ required: true }).extend({ pattern: '[\S]', message : 'cannot contain spaces' });

But no luck.

I can see validation bindings mentions validation messages, but it appears to be for a single message for all validation.

And custom validation rules seems over kill, as all I want is a pattern but with a different message.

Am I missing something obvious?

Carnivorous answered 27/3, 2013 at 11:4 Comment(0)
B
12

Your syntax is wrong. You need to assign an object to the pattern property which contains the message and the params

So the correct usage is:

self.UserName = ko.observable("")
    .extend({ required: true })
    .extend({ pattern: {
         message: 'cannot contain spaces',
         params: '[\S]'
}});

Se also the Getting Started example.

Bracey answered 27/3, 2013 at 11:23 Comment(1)
Bugger, can't believe I missed that! Thanks,Carnivorous

© 2022 - 2024 — McMap. All rights reserved.