Search code examples
javascriptregexknockout.jsknockout-validation

Regular expression still allowing tab character to be pasted into form field


Does anyone know why my regex below is still allowing a tab character whitespace to be pasted into a form field? I think I wrote it correctly...

/^[a-zA-Z\s]+$/g

Suggestion from answer to post:

self.City = ko.observable(model.City).extend({ required: true, maxLength: 30, pattern: /^[a-zA-Z ]+$/ });

Solution

  • \s allows a tab and many more whitespace chars.

    If you need a literal space replace \s with a space.

    You do not need the global modifier either.

    Use

    /^[a-zA-Z ]+$/
    

    In Knockout, use

    self.City = ko.observable(model.City)
        .extend({ required: true })
        .extend({ maxLength: 30 })
        .extend({ pattern: {
                  message: 'Only letters and spaces are allowed.',
                  params: '^[a-zA-Z ]+$'
         }});