Knockout Regex validation

Lemuel Nitor picture Lemuel Nitor · Jun 3, 2013 · Viewed 11.4k times · Source

I am using Knockout.validation to validate my input fields in my page. At first, everything is going well until I tried to use regex. I really don't know what it is that I'm doing wrong, hope you can help me out.

Below is my script:

var self = this;
self.MobileNumber = ko.observable().extend({ pattern: { params: "^(?:04\d{2}|\({1}04\d{2}\){1})\s{0,1}(\d{3}(\s{0,1})\d{3})$", message: "Invalid mobile number."} });

And below is my HTML page:

<div>
    <input data-bind="value: MobileNumber, valueUpdate: 'blur'" />
</div>
<div>
    <p data-bind="validationMessage: MobileNumber">
    </p>
</div>

Answer

Brian Lowe picture Brian Lowe · Jun 3, 2013

The regex needs to be declared as a regex rather than a string, so instead of your line above I'd use

self.MobileNumber = ko.observable().extend({ 
    pattern: { 
        params: /^(?:04\d{2}|\({1}04\d{2}\){1})\s{0,1}(\d{3}(\s{0,1})\d{3})$/, 
        message: "Invalid mobile number."
    } 
});

In my own code I habitually set up an object of regex patterns to make it easy to reuse across my app...

var patterns = {
    email: /^([\d\w-\.]+@([\d\w-]+\.)+[\w]{2,4})?$/,
    phone: /^\d[\d -]*\d$/,
    postcode: /^([a-zA-Z]{1,2}[0-9][0-9]?[a-zA-Z\s]?\s*[0-9][a-zA-Z]{2,2})|(GIR 0AA)$/
};

Then my ko looks like...

self.postcode = ko.observable().extend({
     required: true,
     pattern: {
         message: 'Must be a valid UK postcode',
         params: patterns.postcode
     }
});