Conditional Validation Pattern Match

36 views
Skip to first unread message

Andrew McShane

unread,
Jun 19, 2017, 8:58:47 AM6/19/17
to KnockoutJS
Hi all, I am trying to conditionally validate an address postcode against a specific RegEx but I only want to do this if my postcode is a UK postcode. Something does have to be entered so it is a required field but the pattern should not always apply. So far I have gotten this;

    self.PostCode = ko.observable().extend(
        {
            required: true,
            maxLength: 20,
            pattern: patterns.postcode
        });

This works fine for a UK format postcode but not anything else

I have also tried this;

    self.PostCode = ko.observable().extend(
        {
            required: { onlyIf: function () { self.CountryId === "GB" } },
            maxLength: 20,
            pattern: patterns.postcode
        });

But this does not work.

Anybody got any pointers/ideas?


Andrew McShane

unread,
Jun 19, 2017, 10:19:01 AM6/19/17
to KnockoutJS
No matter, finally figured it out myself with this

    self.PostCode = ko.observable().extend(
    {
        required: true,
        maxLength: 20,
        pattern: ko.pureComputed(function() { 
            return self.CountryId() === 'GB' ? patterns.postcode : ''
        })
    })
Reply all
Reply to author
Forward
0 new messages