Knockout check with regular expression to check phone number

I am trying to add a simple regex check to one of my observables using a knockout check.

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, whatever I enter, it returns the message "Invalid phone number." Is there any way to format an expression? I tested it using only JavaScript and it works great.

+5
source share
3 answers

You need to avoid backslashes, otherwise javascript will treat your single backslash as an escape character for the next character. This is because it is a string, not a regular expression literal.

: , , :

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})$/            
    }
});

params: '^\\D?(\\d{3})\\D?\\D?(\\d{3})\\D?(\\d{4})$'
+11

,

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

.

+4

See the working example below in jsfiddle using a regex that allows spaces and + and () along with the number following the link

jsfiddle.net/JoelDerrick/f6g8npv6/1/

0
source

All Articles