Search code examples
javascriptregexknockout.jsknockout-validation

Why is this pattern not working with knockout validation? (delimited zip codes)


This clearly works on every regex tester I can find, as well as with jquery validation and MVC attributes. What am I missing? I have tried the literal as well as the RegExp but the most I get is validating the first 5 are numeric but other than that either fails anything else or nothing else.

example: https://regex101.com/r/gS0wP0/1

regex: /(\d{5}(\s?)*,?(\s?)*)+/

ko.observable().extend({ pattern: { message: 'Test Message', params:/(\d{5}(\s?)*,?(\s?)*)+/ } });

Solution

  • The RegularExpressionAttribute which is used in ASP.NET MVC implicitly checks for a full length match starting from the first index.

    So it is essentially converting your the pattern to: /^(\d{5}(\s?)*,?(\s?)*)+$/

    However the KO validation is only working with the provided pattern without any additional logic, there you need to manually add the ^ and $ to match for the whole line:

    ko.observable().extend({ 
        pattern: { 
           message: 'Test Message', 
           params:/^(\d{5}(\s?)*,?(\s?)*)+$/ } 
    });