使用正则表达式进行敲除验证以验证电话号码 [英] Knockout-Validation Using Regular Expression to Validate a Phone Number
问题描述
我正在尝试使用Knockout-Validation向我的一个可观察对象添加一个简单的正则表达式验证.
I am trying to add a simple regular expression validation to one of my observables using Knockout-Validation.
我有以下内容:
self.ContactPhone = ko.observable().extend({
required: true,
pattern: {
message: 'Invalid phone number.',
params: '^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$'
}
});
但是,无论我输入什么,它都会返回消息无效的电话号码".我需要格式化表达式的某种方式吗?我已经使用纯JavaScript测试了它,并且效果很好.
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.
推荐答案
您需要转义反斜杠,否则javascript会将您的一个反斜杠本身视为下一个字符的转义字符.这是因为这是一个字符串,而不是正则表达式文字.
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.
实际上,我刚刚检查了一下,您可以只使用一个正则表达式文字,所以这些都可以做到:
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})$/
}
});
或:
params: '^\\D?(\\d{3})\\D?\\D?(\\d{3})\\D?(\\d{4})$'
这篇关于使用正则表达式进行敲除验证以验证电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!