Knockout-Validation Using Regular Expression to Validate a Phone Number
Asked Answered
G

3

7

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.

Gawk answered 2/4, 2013 at 19:29 Comment(0)
G
12

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})$'
Gibun answered 3/4, 2013 at 4:30 Comment(0)
F
7

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

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

More listed here.

Fibrillation answered 7/3, 2014 at 19:33 Comment(1)
Do you know why phoneUS isn't listed on the official Knockout Validation website - github.com/Knockout-Contrib/Knockout-Validation/wiki/… ?Pestana
M
0

See the below working example in jsfiddle using regular expression that allows whitespace and + and() along with number following link

jsfiddle.net/JoelDerrick/f6g8npv6/1/

Mitsue answered 30/6, 2015 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.