Knockout-Validation Using Regular Expression to Validate a Phone Number

烈酒焚心 提交于 2020-01-03 12:34:53

问题


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.


回答1:


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})$'



回答2:


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

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

More listed here.




回答3:


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/



来源:https://stackoverflow.com/questions/15772708/knockout-validation-using-regular-expression-to-validate-a-phone-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!