Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

javascript - How can I use preg_match in jQuery?

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" />

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(/w+/);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...