Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout-Validation Using Regular Expression to Validate a Phone Number

I am trying to add a simple regular expression validation to one of my observables using Knockout-Validation.

I have the following:

self.ContactPhone = ko.observable().extend({
            required: true,
            pattern: {
                message: 'Invalid phone number.',
                params: '^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$'
            }
        });

However, no matter what I enter, it returns the message 'Invalid phone number.' Is there a certain way I need to format the expression? I've tested it using purely JavaScript and it works fine.

like image 732
ThreadedLemon Avatar asked Apr 02 '13 19:04

ThreadedLemon


2 Answers

You need to escape your backslashes otherwise javascript treats your one backslash itself as an escape-character for the next character. This is because this is a string and not a regexp literal.

Edit: Actually I just checked, and you can just use a regexp literal instead, so either of these would do it:

http://jsfiddle.net/antishok/ED3Mh/2/

self.ContactPhone = ko.observable().extend({
    required: true,
    pattern: {
        message: 'Invalid phone number.',
        params: /^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/            
    }
});

or:

params: '^\\D?(\\d{3})\\D?\\D?(\\d{3})\\D?(\\d{4})$'
like image 134
antishok Avatar answered Oct 05 '22 19:10

antishok


In case you dont have to use Regular Expression, here is the native way

self.ContactPhone = ko.observable().extend({ phoneUS : true });

More listed here.

like image 36
Jeson Martajaya Avatar answered Oct 05 '22 21:10

Jeson Martajaya