问题描述
我可以使用preg_match来验证jQuery中的电话号码吗?这是我的代码不起作用
if(!preg_match(/ ^ [0-9] {3} - | \ [0-9] {3} - | \ [0-9] {4} $ /,phone.val())){
phone.addClass(needsfilled);
phone.val(phonerror);
}
HTML
< input id = phonetype =textvalue =name =phone/>
任何人都可以帮助plz
Javascript包含一个正则表达式引擎,可通过 string.match()$ c $访问c>,
string.replace()
和 string.split()
functions。
例如:
var mystring =这是一个句子;
mystring = mystring.replace(/ sentence /,'string');
var matches = mystring.match(/ \ b\w + \b /);
这应该为您提供与 preg_match()相同的功能
。
所以要在你的问题中进行与preg_match相同的验证:
<$ p $ !p>
如果(phone.val()匹配(/ ^ [0-9] {3} - | \s [0-9] {3} - | \s [O- 9] {4} $ /)){
phone.addClass(needsfilled);
phone.val(phonerror);
}
如果您绝对坚持使用名为的函数preg_match ()
与PHP版本完全相同,有一个名为的项目,旨在实现PHP函数的JavaScript。快速查看他们的网站显示,尽管他们目前没有完全正常工作的 preg_match()
实现,但他们有一个,您可能需要查看。但坦率地说,内置的Javascript .match()
函数应该足够了。
Can i use preg_match to validate phone number in jQuery? Here is my code which does not work
if (!preg_match("/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/", phone.val() )) {
phone.addClass("needsfilled");
phone.val(phonerror);
}
HTML<input id="phone" type="text" value="" name="phone" />
Could any one help plz
Javascript includes a regular expression engine, which is accessed via the string.match()
, string.replace()
and string.split()
functions.
For example:
var mystring = "this is a sentence";
mystring = mystring.replace(/sentence/,'string');
var matches = mystring.match(/\b\w+\b/);
That should provide you with essentially the same functionality as preg_match()
.
So to do the same validation as the preg_match in your question:
if(!phone.val().match(/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/)) {
phone.addClass("needsfilled");
phone.val(phonerror);
}
If you absolutely insist on having a function called preg_match()
which works exactly like the PHP version, there is a project called PHPJS, which aims to implement PHP functions in Javascript. A quick look at their site shows that although they don't currently have a fully working preg_match()
implementation, they have an unfinished implementation which you may want to look at. But frankly, the built-in Javascript .match()
function should be more than sufficient.
这篇关于我怎样才能在jQuery中使用preg_match?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!